哈希是键值对的集合,如下所示:“employee”=>“salary”。它类似于数组,只是索引是通过任何对象类型的任意键完成的,而不是整数索引。
通过键或值遍历哈希的顺序可能看起来是任意的,并且通常不会在插入顺序中。如果您尝试使用不存在的键访问哈希,该方法将返回 nil。
哈希用于存储大量(或少量)数据并有效地访问它。例如,假设您将其作为哈希:
prices = {
'orange' => 3.15,
'apple' => 2.25,
'pear' => 3.50
}
现在您想调用关键字apple 并从某些用户输入中获取这些商品的价格:
print 'Enter an item to verify price: '
item = gets.chomp
puts "The price of an #{item}: #{prices[item]}"
# <= The price of an apple: 2.25
这是一个基本的哈希,现在让我们来看看你在做什么,使用 Array 作为键。
prices = {
'apple' => ['Granny Smith', 'Red'],
'orange' => ['Good', 'Not good'],
'pear' => ['Big', 'Small']
}
print 'Enter an item for a list: '
item = gets.chomp
puts "We have the following #{item}'s available: #{prices[item]}"
# <= We have the following apple's available: ["Granny Smith", "Red"]
现在,如果我们想获取其中一种类型:
puts prices[item][0]
# <= Granny Smith
puts prices[item][1]
#<= Red
现在让我们进入更高级的技术,就像你在上面做的那样,你的想法很棒,但你需要做的是将信息附加到hash,当你打电话给@name时不要尝试将其称为符号:
h = Hash.new{|hsh,key| hsh[key] = [] }
h[@name] = []
#<= []
h[@name] << ['apple', 'pear']
#<= [["apple", "pear"]]
h[@name] << ['orange', 'apple']
#<= [["apple", "pear"], ["orange", "apple"]]
h[@name].flatten[0]
#<= "apple"
h[@name].flatten[1]
#<= "pear"
h[@name].flatten[1, 2]
#<= ["pear", "orange"]
好吧,那我们做了什么?
h = Hash.new{|hsh,key| hsh[key] = [] }
创建了一个hash,其值为空array。
h[@name] = []
将@name初始化为空array
h[@name] << ['apple', 'pear']
将包含apple, pear 的数组附加到@name 键。
h[@name] << ['orange', 'apple']
将包含orange, apple 的第二个array 附加到数组中,因此当我们现在调用h[@name][1] 时,它将输出附加到它的第一个array。
h[@name].flatten[0]
将array 扁平化为一个数组并调用array 的第一个元素。
当您调用密钥 (@name) 时,您不会将其称为符号,因为它已经包含在变量中。因此,您所要做的就是调用该变量,该键的值将成功输出。希望这可以澄清一些事情,有关hashes的更多信息,请查看:http://www.tutorialspoint.com/ruby/ruby_hashes.htm