1

I'm pretty new to Ruby (I come from a C++ background) and I have an array/hash of objects by their name but I'm having no luck when trying to access their variables. This is my attempt:

class Foo
attr_reader :num

def initialize(num)
    @num = num
end
end

foo_list = {}

foo_list["one"] = Foo.new("124")
foo_list["two"] = Foo.new("567")

foo_list.each do |foo|
p "#{foo.num}"              # ERROR: undefined method 'num'
end

I'm pretty sure there is an easy way of doing what I need, maybe not even using 'each' but something else?

2
  • 1
    Just a word of advice, you can print out foo in the block to see what foo actually is. Also, Ruby documentation is pretty good. Just googling for "ruby hash" then looking up the each method, would have put you on the right track. ruby-doc.org/core-2.0/Hash.html#method-i-each Commented Jun 8, 2013 at 17:21
  • Or, if you let Ruby build its built-in documentation, ri Hash at the command-line would show the various methods. ri Hash.each would have given more information specific to each. Commented Jun 8, 2013 at 18:06

2 Answers 2

4

You might be looking for this:

foo_list.each do |key, value|
  puts "#{key}: #{value}"
end

Or you can extend your own example (foo would be an array here containing the key and value):

foo_list.each do |foo|
  puts "#{foo[0]}: #{foo[1]}"
end

Or you could do this without the each:

puts "one: #{foo_list["one"]}"
puts "two: #{foo_list["two"]}"

Have fun learning Ruby! :-)

Sign up to request clarification or add additional context in comments.

Comments

1

Shouldn't that be foo_list.each do |key, foo|, given that foo_list is a hash?

1 Comment

OMG, I feel stupid, there goes an hour of my life on this. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.