Robert Rodriguez
Robert Rodriguez

Reputation: 191

Hash/Array of objects in Ruby

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?

Upvotes: 1

Views: 1459

Answers (2)

kaspernj
kaspernj

Reputation: 1263

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! :-)

Upvotes: 4

Denis de Bernardy
Denis de Bernardy

Reputation: 78561

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

Upvotes: 1

Related Questions