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




















Hash Sample




















声明:该文观点仅代表作者本人,牛骨文系教育信息发布平台,牛骨文仅提供信息存储空间服务。
- 上一篇: Ruby中的数组过滤
- 下一篇: ruby入门_并行赋值_数组