Good day. I study Ruby, do not kick hard, just started.

Why in the say_hi method in the parameter (in parentheses) the variable is not of type "@name" (object variable), but does the method still work? As far as I understand, because there is attr_accessor, but the parameter is not an object variable, how does the method understand what is passed to it?

class Person attr_accessor :name def initialize(name) @name = name end def say_hi puts "hi #{name}" end end person_one = Person.new("Ivan") person_one.say_hi person_one.name = "Petr" person_one.say_hi 
  • 2
    If you are given an exhaustive answer, mark it as correct (tick the selected answer). - Mikhail Vaysman

1 answer 1

 attr_accessor :name 

Adds a method to your class.

  def name @name end 

Therefore, you can access the variable using this method.

  • why it works without a dog? def say_hi puts "hi # {name}" end - user233110
  • Without @ is a method call. With @ is a reference to a variable. - Mikhail Vaysman