0

I have a custom object, very simple jsut to try and figure out how ruby works.

    class SomeObject
  def initialize(name)
    @myName = name
  end

  def sayHello
    puts 'Hello ' + @myName
  end
end

I'm then running a search using chef, and creating several of these objects and adding them to a collection : collection = [] and then collection << myObject where myObject is myObject = SomeObject.new('someName')

I'm them trying to iterate over this collection, get the object and call sayHello.

collection.each do |i|
  p "Something...."
  p i.name #fails
  #i.sayHello # fails

end

Can anyone tell me where I'm going wrong or how I might achieve this? Thanks.

Edit: If I print 'i' to the screen I get

<#::SomeObject:0x00000005546a50 @myName="some-name">

So I'm sure its being created and is in the collection, i jsut can't get the thing out :D

null
  • 3,469
  • 7
  • 41
  • 90

1 Answers1

3

Your instance variable is named @myName not @name, additionally you need to allow your instance variable to be read publicly using the attr_reader directive:

class SomeObject
  attr_reader :myName

  def initialize(name)
    @myName = name
  end

  def sayHello
    puts 'Hello ' + @myName
  end
end

collection = [ SomeObject.new('Hunter') ]
collection.each do |i|
  puts i.myName # output= Hunter
  i.sayHello()  # output= Hello Hunter
end
Community
  • 1
  • 1
Hunter McMillen
  • 59,865
  • 24
  • 119
  • 170