一个哈希是这样的键值对的集合:“雇员” =>“工资”。它与数组类似,只不过索引是通过任意对象类型的任意键完成的,而不是整数索引。
您用键或值遍历散列的顺序可能看起来是任意的,并且通常不会处于插入顺序中。如果您尝试使用不存在的键访问散列,则该方法将返回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
追加含有apple, pear
到@name
密钥的阵列。
h[@name] << ['orange', 'apple']
追加第二array
含有orange, apple
到阵列,所以当我们现在称之为h[@name][1]
它将输出第一array
附加到它。
h[@name].flatten[0]
变平array
成一个单一的阵列,并且被称为array
的第一个元素。
当您呼叫您的密钥(@name
)时,您不会将其称为符号,因为它已包含在变量内。所以你所要做的就是调用该变量,并且该键的值将被成功输出。希望这个澄清一些东西,关于hashes
更多的信息检查了这一点:http://www.tutorialspoint.com/ruby/ruby_hashes.htm
真的很感谢详细的答案 –