【问题标题】:Get the name of a hash that is inside an array being mapped over in Ruby获取在 Ruby 中映射的数组内的哈希名称
【发布时间】:2014-01-22 22:21:47
【问题描述】:

我以为我可以简单地做到这一点,但我似乎在使用这种方法时遇到了障碍,而且我知道 Ruby 很棒并且有一个解决方案;像往常一样。

我计划创建一些 YAML 文件来跟踪用户在 IRC 上说的单词以及他们说这些单词的次数,以及一个更大的文件,它基本上是所有这些单词的串联。在开始之前,我决定测试我的方法并让基础知识发挥作用。

以下是我在意识到将哈希存储在数组中时的想法,它并没有将其存储为哈希名称,而是将代码存储在哈希值中。

如何获取数组中每个元素的哈希名称?

irb(main):006:0> bob = {'a' => 1, 'b' => 2}
=> {"a"=>1, "b"=>2}
irb(main):008:0> sally = {'hey' => 5, 'rob' => 10}
=> {"hey"=>5, "rob"=>10}
irb(main):023:0> words = [bob, sally]
=> [{"a"=>1, "b"=>2}, {"hey"=>5, "rob"=>10}]
irb(main):024:0> words.map{|person| person.map{|word,amount| puts "#{person} said #{word} #{amount} times"}} 
{"a"=>1, "b"=>2} said a 1 times
{"a"=>1, "b"=>2} said b 2 times
{"hey"=>5, "rob"=>10} said hey 5 times
{"hey"=>5, "rob"=>10} said rob 10 times

【问题讨论】:

    标签: ruby arrays hash map


    【解决方案1】:

    bob, sally 是局部变量,它们没有名称。局部变量没有名称。所以你不能按照你尝试的方式得到它。

    我认为如下:

    bob = {"a"=>1, "b"=>2}
    sally = {'hey' => 5, 'rob' => 10}
    words = %w[bob sally] # => ["bob", "sally"]
    words.map do |person| 
      eval(person).map{|word,amount| puts "#{person} said #{word} #{amount} times"}
    end
    
    # >> bob said a 1 times
    # >> bob said b 2 times
    # >> sally said hey 5 times
    # >> sally said rob 10 times
    

    【讨论】:

    • 我完全明白这不再有意义了。 v = '一个';这与试图找出“a”属于什么是一样的,这是不可能的,因为以下问题: v = 'a'; b = 'a';变量的值不知道去哪里看,是v还是b?抱歉这个愚蠢的问题。
    猜你喜欢
    • 2013-12-18
    • 1970-01-01
    • 2014-08-09
    • 2021-02-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-11
    相关资源
    最近更新 更多