首页 > 代码库 > 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 
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