首页 > 代码库 > ruby学习之Hash
ruby学习之Hash
一、定义:
hsh=Hash.new
hsh=Hash[1=>”a”,2=>”b”]
hsh={“1”=>”a”,2=>”b”}
支持任意对象为key,习惯使用Symbol
二、常用方法
#!/usr/bin/ruby def printResult(args) print args puts "" end hsh={:a=>"hello",:b=>"world"} puts hsh # hsh.clear() # puts hsh hsh.delete(:a) puts hsh hsh[:c]="third" puts hsh hsh.delete_if(){|key,value| value=http://www.mamicode.com/="third"} >result:
{:a=>"hello", :b=>"world"}
{:b=>"world"}
{:b=>"world", :c=>"third"}
{:b=>"world"}
true
true
{"world"=>:b}
[:b, :d, :e]
["world", "ddd", "eee"]
["world", "ddd"]
3
{:b=>"bbbb", :d=>"ddd", :e=>"eee", :f=>"ffff"}
{:b=>"b2b2b2", :g=>"ggg"}
[[:b, "b2b2b2"], [:g, "ggg"]][Finished in 0.1s]
三、查找和迭代
Hash是可枚举类型的对象,具有其搜索遍历和排序的能力,参见ruby之Enumerable
#!/usr/bin/ruby def printResult(args) print args puts "" end hsh={:a=>1,:b=>2,:c=>5,:d=>4} printResult hsh.find_all(){|key,value| value > 2} printResult hsh.map { |key,value| key } printResult hsh.max printResult hsh.sort printResult hsh.sort_by(){|key,value| value} hsh.each do |key,value| print key end puts "" hsh.each_key() do |key| print key end puts "" hsh.each_value() do |value| print value endresult:
[[:c, 5], [:d, 4]]
[:a, :b, :c, :d]
[:d, 4]
[[:a, 1], [:b, 2], [:c, 5], [:d, 4]]
[[:a, 1], [:b, 2], [:d, 4], [:c, 5]]abcd
abcd
1254
[Finished in 0.1s]
ruby学习之Hash
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。