Forum: Ruby Not sure why this is failing, barring a typo:

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
0765080a8d48afe94f0903f7adb00c9c?d=identicon&s=25 yuckysocks (Guest)
on 2009-01-25 02:00
(Received via mailing list)
This code, directly from a book:

class Animal
  def initialize(color)
    @color = color
  end

  def get_color
    return @color
  end
end

animal = Animal.new("brown")
puts "The new animal is " + animal.color

results in "undefined method: color". But aren't I defining the method
as part of the constructor? Maybe I just don't understand what I'm
doing... anyhow, help would be appreciated!  :)

-Alex
D337e2cf7c6d03caac6988d83e0e7f66?d=identicon&s=25 Michael Guterl (mguterl)
on 2009-01-25 02:08
(Received via mailing list)
On Sat, Jan 24, 2009 at 7:58 PM, yuckysocks <alex.m.mcpherson@gmail.com>
wrote:
> end
>
> animal = Animal.new("brown")
> puts "The new animal is " + animal.color
>
> results in "undefined method: color". But aren't I defining the method
> as part of the constructor? Maybe I just don't understand what I'm
> doing... anyhow, help would be appreciated!  :)
>
Your method is named get_color, you're trying to call the method
color.  Make sure they match and it should work.

HTH,
Michael Guterl
F778607e066c8372ab94b0920ed7b2b8?d=identicon&s=25 Jakub Pavlík jn. (Guest)
on 2009-01-25 02:11
(Received via mailing list)
> end
>
> animal = Animal.new("brown")
> puts "The new animal is " + animal.color
>
> results in "undefined method: color". But aren't I defining the method
> as part of the constructor? Maybe I just don't understand what I'm
> doing... anyhow, help would be appreciated!  :)
>
> -Alex

No.
@color = color
just defines instance variable, which can't be accessed from outside.
You must define reader method:

attr_reader :color

or

def color
  return @color
end

--
"Configure complete, now type 'make' and PRAY."

                (configure script of zsnes - www.zsnes.com)
This topic is locked and can not be replied to.