一、定义:
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=="third"} puts hsh puts hsh.has_key?(:b) puts hsh.has_value?("world") puts hsh.invert() hsh[:d]="ddd" hsh[:e]="eee" printResult hsh.keys() printResult hsh.values printResult hsh.values_at(:b,:d) puts hsh.length() puts hsh.merge({:b=>"bbbb",:f=>"ffff"}) puts hsh.replace({:b=>"b2b2b2",:g=>"ggg"}) print hsh.to_a()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]
时间: 2024-10-23 00:54:39