Not sure why this is failing, barring a typo:

Y

yuckysocks

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
 
M

Michael Guterl

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

Jakub Pavlík jn.

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

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,767
Messages
2,569,570
Members
45,045
Latest member
DRCM

Latest Threads

Top