Ruby之旅(七) 数组以及Hash

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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值