【问题标题】:printing out the values of a hash coming from an array打印出来自数组的哈希值
【发布时间】:2015-11-02 08:25:51
【问题描述】:

我有一个名为sales_hash 的哈希值,我正在打印出来。每个散列都有一个名为sku 的键,它与array_items 数组中的散列匹配。我从数组中取出散列,并尝试根据 :item 的键打印散列的值,但我不断收到错误消息。我做错了什么?

sales_hash.take(10).each do |a, b|
  temp_hash = array_items.select{|array_items| array_items[:sku] == a}
  puts temp_hash
  puts "Sku is #{a} the amount sold is #{b} the name of the book is #{temp_hash[:price]}"
end

#{temp_hash[:item]}" 行一直给我一个错误

【问题讨论】:

  • 错误信息是什么?
  • 做:puts temp_hash.inspect 看看你在temp_hash里面得到了什么
  • @DJ 错误信息是 rb:59:in `[]': no implicit conversion of Symbol into Integer (TypeError)
  • @KMRakibulIslam,我得到了项目的哈希 [{:item=>["cornish_heath"], :price=>24.33, :sku=>236131}]
  • 那不是散列,那是散列数组。

标签: arrays ruby hash


【解决方案1】:

您的temp_hash 实际上是一个数组。

来自Docs

select -> 返回一个新数组,其中包含给定块返回真值的 ary 的所有元素。

而且你不能像这样访问数组:array[:key]。

【讨论】:

    【解决方案2】:

    由于temp_hash 是一个数组,并且您确定该数组中只有一个项目,因此获取 temp_hash 内容的正确方法是使用“first”,如下所示:

    #{temp_hash.first[:price]}

    【讨论】:

      【解决方案3】:

      由于您的 temp_hash 是一个数组,因此您可以像这样访问预期的哈希:

      temp_hash[0] # this will give you the expected hash data
      

      然后,您可以访问散列中所需的密钥(例如price):

      temp_hash[0][:price]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-06-24
        • 2020-10-16
        • 2014-11-30
        • 2016-02-21
        • 2012-07-22
        • 1970-01-01
        • 2014-05-11
        相关资源
        最近更新 更多