Ruby支持数组以及Hash,数组和Hash都是通过索引访问的,所不同的是数组通过数字索引,而Hash的索引可以是任何对象,所以数组访问速度更快(直接定位),而Hash则更加灵活,搜索元素速度更快(Hash算法定位索引,无需遍历)。
Ruby里面比较有特点的是,数组与Hash都可以容纳不同的对象,因为这是Ruby语言所决定的(非强类型语言,单根派生自Object)
数组的一个常用方法是<< 这个方法的作用是添加一个元素在数组中。
sample
class
MyClass
def
to_s
return
"
LeeClass
"
end
end

arr
=
%
w[How are you.]
#
The same as arr = ["How", "are", "you."]
arr
<<
"
I'm
"
#
Append a element
arr
<<
MyClass.new
arr.each do
|
item
|
if
item.
class
.to_s.upcase
!=
"
STRING
"
print
"
#{item}, Type:#{item.class}
"
else
print
item
+
"
"
end
end
#
output: How are you. I'm LeeClass, Type:MyClass
Hash Sample
class
MyClass
def
to_s
return
"
hallo
"
end
end
mc
=
MyClass.new
hash
=
{
:maozedong
=>
"
laoda
"
,
:zhouenlai
=>
"
laoer
"
,
:jiangjieshi
=>
"
fool
"
,
mc
=>
mc
}

puts hash[:maozedong].
class
.to_s
#
output String
puts hash[:maozedong]
#
output laoda
puts hash[mc].
class
.to_s
#
output MyClass
puts hash[mc]
#
output hallo because the puts method default calling to_s
本文介绍了Ruby语言中数组和Hash的使用方法,包括数组的创建、添加元素以及Hash的定义和访问方式。通过示例代码展示了如何使用Ruby的<<方法添加元素到数组,并演示了如何使用自定义类的实例作为Hash的键。
410

被折叠的 条评论
为什么被折叠?



