R
R
RaMzz2018-03-18 14:41:54
ruby
RaMzz, 2018-03-18 14:41:54

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")

how can I just set the Attribute in the move method because it is in the class
def move(destination)
with this line I just assign the attribute
dog.move("bad")
why can't I do it with name I 'm confused in
general help me figure it out ..
Not much is cleared up, but I can't understand why the first two methods are written like this
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

def name=(value)
def age=(value)
And here is the
def move(destination)
method like this without equals =

Answer the question

In order to leave comments, you need to log in

1 answer(s)
Z
Zaporozhchenko Oleg, 2018-03-18
@RaMzz

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

attr_writer :name declares
def name=(value)
  @name = value
end

attr_accessor :name will declare both methods at once. move for you is already a method that works with internal data, it encapsulates them. Therefore it is declared as a method.
In fact, in ruby ​​all methods, in ruby ​​from the outside it is impossible to read the attribute without declared methods. move is similar to just a method familiar from other PLs. Its task is to hide the internal implementation of the class and provide an interface for working with it.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question