Need a little help

Hey Guys,
New to ruby & working on a few tutorials & I’m having trouble with
getting the following code to work & I can’t figure out why?

class Animal
attr_accessor :name
attr_writer :color
attr_reader :legs, :arms

def setup_limbs
@legs = 4
@arms = 0
end

def noise=(noise)
@noise = noise
end

def color
“The color is #{@color}.”
end
end

animala = Animal.new
animala.setup_limbs
animala.noise = “Moo!”
animala.name = “Steve”
puts animala.name
animala.color = “black”
puts animala.color
puts animala.legs
puts animala.noise

animalb = Animal.new
animalb.noise = “Quack!”
puts animalb.noise

I’ve double checked the tutorial (video) & every piece seems to be
correct but where the tutorial works in the video I can’t!

Thanks,
Tom

On Dec 10, 2012, at 6:28 PM, tom mr wrote:

@legs = 4
@arms = 0
end

def noise=(noise)
@noise = noise
end

This sets @noise, but there’s no method for getting the noise back.

You probably need to add either:
attr_reader :noise
(or just att , :noise following the :legs, :arms in the earlier one)

Or define your own getter like was done for color.

-Rob

Setter:

def some_var_name=(val)
@some_var_name = val
end

Getter:

def some_var_name
@some_var_name
end

To set a value, there has to be a setter defined. To retrieve a value,
e.g.

puts obj.some_var_name

there has to be a getter defined. You can make ruby define both the
setter and getter for you by including the following in your class:

attr_accessor :some_var_name

That is equivalent to explicitly writing the getter and setter shown
above. Or, if you don’t want people to be able to set the value, you
can define
only the getter:

attr_reader :some_var_name

That is equivalent to defining the getter shown above. Similarly using
attr_writer in your class is equivalent to defining the setter shown
above.

You’re also going to want to consider putting an initialize statement in
there for when the object is created.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs