Answer the question
In order to leave comments, you need to log in
Why do I have access to an instance method attribute?
I’m reading a book and already on the hundredth page I’m at an impasse I don’t understand why I can change the attribute of the instance method
class Dog
attr_reader :name, :age
def name=(value)
if value == ""
raise "Name can't be blank!"
end
@name = value
end
def age=(value)
if value < 0
raise "An age of #{value} isn't valid!"
end
@age = value
end
def move(destination)
puts "#{@name} runs to the #{destination}."
end
def talk
puts "#{@name} says Bark!"
end
def report_age
puts "#{@name} is #{@age} years old."
end
end
dog = Dog.new
dog.name = "Daisy"
dog.age = 3
dog.report_age
dog.talk
dog.move("bad")
def name=(value)
if value == ""
raise "Name can't be blank!"
end
@name = value
end
def age=(value)
if value < 0
raise "An age of #{value} isn't valid!"
end
Answer the question
In order to leave comments, you need to log in
attr_reader :name is not about setting read permissions. It's just a shorthand for declaring a method, all it does is declare a read method itself, analogous to
def name
@name
end
def name=(value)
@name = value
end
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question