Reputation: 281
I thought I could simply do this, but I seem to have hit a road block with this approach, and I know Ruby is amazing and there is a solution; as usual.
I plan on creating some YAML files to keep track of words that users say on IRC and the amount of times they said those words, as well as a larger file which is basically a concatenation of them all. I decided before I started I would test out my approach and get the basics working.
Below is what I have come up with before realizing that when storing a hash inside of an array, it didn't store it as the hashes name, it instead stored the code from within the hash values.
How could I grab the hash name for each element inside the array?
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
Upvotes: 0
Views: 51
Reputation: 118289
bob, sally
are local variables, they don't have names.Local variables don't have names. So you can't get it the way you are trying.
I think something like below :
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
Upvotes: 2