標籤: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 "" endhsh={: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 "" endhsh={: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 end
result:
[[: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