【问题标题】:Access Hash with multiple values ruby使用多个值 ruby​​ 访问哈希
【发布时间】:2016-07-29 15:03:57
【问题描述】:

我有一个哈希

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

并且它的值被存储为一个数组

Iv 像这样添加到键的值数组中:

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

我试图像这样访问年龄

puts h[:@name][0]

但它不起作用?

有更好的方法吗?

我试图做的是创建一个散列,其中有一个包含大量值的键: 例如key=&gt;name 和值等于ageaddressgender

【问题讨论】:

    标签: ruby


    【解决方案1】:

    恕我直言,您的想法没问题。 唯一的错误是..您如何访问哈希。无需在@ 符号前添加额外的冒号:

    删除冒号,它应该可以正常工作:

    puts h[@name][0]
    

    【讨论】:

      【解决方案2】:

      哈希是键值对的集合,如下所示:“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

      【讨论】:

      • 非常感谢详细解答
      猜你喜欢
      • 1970-01-01
      • 2014-04-09
      • 2017-07-08
      • 1970-01-01
      • 2013-04-18
      • 2013-07-21
      • 1970-01-01
      • 2012-05-14
      • 1970-01-01
      相关资源
      最近更新 更多