2014-01-05 46 views
0

我認爲我可以簡單地做到這一點,但我似乎用這種方法碰到了一個路障,我知道Ruby很棒,並且有一個解;照常。獲取在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 

回答

3

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 
+0

我完全看不出這沒有任何意義了。 v ='a';這與試圖找出'a'屬於什麼一樣,這是不可能的,因爲這樣的問題:v ='a'; b ='a';變量的值不知道在哪裏看,是v還是b?對不起,這個愚蠢的問題。 – Singularity

相關問題