一.数据类型:
数值类型(integer、浮点型(算数操作:+-*/ )、String类型、数组、哈希类型、范围类型)
1.1数组的字面量[]中以逗号隔开,支持range定义
(1)数组通过[]索引访问
(2)通过赋值操作插入、删除、替换元素
(3)通过+,-号进行合并和删除元素,且集合做为新集合出现
(4)通过<<号向原数据追加元素
(5)通过*号重复数组元素
(6)通过|和&符号做并集和交集操作(注意顺序)
Ruby 数组可存储诸如 String、 Integer、 Fixnum、 Hash、 Symbol 等对象,甚至可以是其他 Array 对象。
Ruby 数组不需要指定大小,当向数组添加元素时,Ruby 数组会自动增长。
创建数组: names=Array.new
names=Array.new(20)
1.2 哈希类型{key,value}
#!/usr/bin/ruby
hsh = colors = { "red" => 0xf00, "green" => 0x0f0, "blue" => 0x00f }
hsh.each do |key, value|
print key, " is ", value, "\n"
end
运行的结果如下:
red is 3840
green is 240
blue is 15
1.3范围类型
范围可使用 s..e 和 s…e 来构造,或者通过 Range.new 来构造。
#!/usr/bin/ruby
(10..15).each do |n|
print n, ' '
end
结果
10 11 12 13 14 15