Forum: Ruby Need a little help

Posted by tom mr (snakeawesome)
on 2012-12-11 00:28
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
Posted by Rob Biedenharn (Guest)
on 2012-12-11 00:51
(Received via mailing list)
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
Posted by 7stud -- (7stud)
on 2012-12-11 08:02
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.
Posted by Brandon Weaver (Guest)
on 2012-12-11 08:38
(Received via mailing list)
You're also going to want to consider putting an initialize statement in
there for when the object is created.
Please log in before posting. Registration is free and takes only a minute.
Existing account (Switch to SSL-encrypted connection)
NEW: Do you have a Google/GoogleMail or Yahoo account? No registration required!
Log in with Google account | Log in with Yahoo account
No account? Register here.