7stud2
(7stud --)
1
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 via http://www.ruby-forum.com/.
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
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
···
On Dec 10, 2012, at 6:28 PM, tom mr wrote:
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 via http://www.ruby-forum.com/\.
7stud2
(7stud --)
3
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 canmake ruby define both the
setter and getter for you if you include the following in your class:
attr_accessor :some_var_name
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
(you can also define the getter manually). Etc.
···
--
Posted via http://www.ruby-forum.com/.
You're also going to want to consider putting an initialize statement in
there for when the object is created.