[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

Not sure why this is failing, barring a typo:

alex.m.mcpherson

1/25/2009 12:58:00 AM

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
2 Answers

Michael Guterl

1/25/2009 1:06:00 AM

0

On Sat, Jan 24, 2009 at 7:58 PM, yuckysocks <alex.m.mcpherson@gmail.com> wrote:
> 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

Jakub Pavlík jn.

1/25/2009 1:09:00 AM

0

> 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

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

(configure script of zsnes - www.zsnes.com)