哈希表(hash)是使用将某一任意对象作为键来对应其他对象的容器对象,相当于C++或Java中的映射。
例1
month_to_ordinal = {
"Jan" =>1, "Feb" =>2, "Mar" =>3, "Apr" =>4, "May" =>5, "Jun" =>6, "Jul" =>7, "Aug" =>8, "Sep" =>9, "Oct" =>10, "Nov" =>11, "Dec" =>12
}
p month_to_ordinal["Aug"]
p month_to_ordinal["Sep"]
#输出结果
#8
#9
创建哈希表
要生成哈希表只需将键和值得对应关系排列在花括号内就可以了。
例2
prefix = "yapoo-"
abbr = {
"CAT" => "Condensed-Abridged Tiger", "Yapomb" => prefix + "womb", "pilk" => prefix + "milk"
}
p abbr["CAT"]
p abbr["Yapomb"]
p abbr["pilk"]
#输出结果
#"Condensed-Abridged Tiger"
#"yapoo-womb"
#"yapoo-milk"
更简单的表示方法,使用符号“:”
例3
params = {rin: 5, kimiko: 7, Kayo:nil}
p params
p params[:rin]
p params[:kimiko]
p params[:Kayo]
#输出结果
#{:rin=>5, :kimiko=>7, :Kayo=>nil}
#5
#7
#nil
索引运算符表达式
例4
book_to_author = {
"Ruby in Nutshell" => "Flanagan",
"Programming in Ruby" => "Thomas",
"AWDwr" => "Thomas"
}
p book_to_author["Programming in Ruby"]
p book_to_author["Programming in Perl"]
#更新已有的键值
p book_to_author["Ruby in Nutshell"] = ["Flanagan", "Matz"]
#添加新的键值
p book_to_author["The Ruby Way"] = "Fulton"
#输出结果
#"Thomas"
#nil
#["Flanagan", "Matz"]
#"Fulton"
哈希表的比较
hash对象之间,只有对象中所有对应的元素间的键和值都相等时才相等,但和顺序无关。
例5
hash1 = {"a" => 1, "b" =>2}
hash2 = {"a" => 1, "b" =>2}
p hash1 == hash2
#和顺序无关,相等
p hash1 == {"b" => 2, "a" =>1}
#值不一样,所以不相等
p hash1 == {"a" => 9, "b" =>2}
#键不一样,所以不相等
p hash1 == {"z" => 1, "b" =>2}
#有多余的内容,所以不相等
p hash1 == {"a" => 1, "b" =>2, "c" => 3}
#输出结果
#true
#true
#false
#false
#false
哈希表的其它方法
例6
book_to_author = {
"Ruby in Nutshell" => "Flanagan",
"Programming in Ruby" => "Thomas",
"AWDwr" => "Thomas"
}
#size方法
p book_to_author.size
#用hash#each方法对哈希表的元素进行处理
book_to_author.each do |book, author|
puts "#{book} by #{author}"
end
#hash#map会将代码块返回的值作为数组返回
p book_to_author.map{|book, author| "#{book} by #{author}"}
#输出结果
#3
#Ruby in Nutshell by Flanagan
#Programming in Ruby by Thomas
#AWDwr by Thomas#["Ruby in Nutshell by Flanagan", "Programming in Ruby by Thomas", "AWDwr by Thomas"]
Enumerable模块
数组和哈希表之间除了map还有很多类似的方法,这是因为不论是数组还是哈希表,都同属于Enumerable这个模块。 Array和Hash都继承了Enumerable。
模块是为了让没有共同的继承的类拥有共同的实现而使用的方法。