2016-07-29 109 views
0

我有一个散列访问哈希红宝石

h = Hash.new{|hsh,key| hsh[key] = [] } 

而其值被存储作为数组

㈣添加到值阵列的关键像这样:

h[@name] << @age 
h[@name] << @grade 

和IM试图访问像这样的年龄

puts h[:@name][0] 

但它不起作用?

有没有更好的方法来做到这一点?

什么即时试图做的是创建一个哈希那里是具有价值负荷的关键: 例如key=>name和值等于ageaddressgender

回答

1

一个哈希是这样的键值对的集合:“雇员” =>“工资”。它与数组类似,只不过索引是通过任意对象类型的任意键完成的,而不是整数索引。

您用键或值遍历散列的顺序可能看起来是任意的,并且通常不会处于插入顺序中。如果您尝试使用不存在的键访问散列,则该方法将返回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

+1

真的很感谢详细的答案 –

5

恕我直言,你的想法是好的。 唯一的错误是..你如何访问散列。不需要在@之前添加额外的冒号:

取出结肠,它应该工作,你希望:

puts h[@name][0]