-1

This question is about setter and getter methods in Ruby. In the example below, I have three methods. The first two are, respectively, to get and set an instance variable @login_method. The third is an instance method that attempts to access the setter method. It fails to access the setter method, because when the line login_method = 15 is run, execution does not stop for the debugger statement I placed inside the setter method. Why can I not access the setter method from inside of method mymeth? I can access it if I prefix the setter method call with "self", but why do I have to do this?

require 'byebug'
class MyClass
  def login_method
    debugger;
    @login_method
  end
  def login_method=(value)
    debugger;
    @login_method
  end
  def mymeth
    debugger;
    login_method = 15
  end
end

obj = MyClass.new
obj.mymeth
evianpring
  • 3,316
  • 1
  • 25
  • 54
  • 1
    From [Assignment Methods](http://ruby-doc.org/core-2.3.1/doc/syntax/assignment_rdoc.html#label-Assignment+Methods): _"When using method assignment you must always have a receiver. If you do not have a receiver, Ruby assumes you are assigning to a local variable"_ – Stefan Jun 08 '16 at 15:22

2 Answers2

1

Your login_method= instance method needs a receiver. If this is not important for you and you can make it private this should do the trick

private

def login_method=(value)
    debugger;
    @login_method
end
Ursus
  • 29,643
  • 3
  • 33
  • 50
1

Try with this:

class MyClass
  def login_method
    @login_method
  end
  def login_method=(value)
    @login_method = value
  end
  def mymeth
    self.login_method = 15
  end
end

obj = MyClass.new
obj.mymeth
puts obj.login_method

You can also do this:

class MyClass
  attr_accessor :login_method

  def mymeth
    self.login_method = 15
  end
end

obj = MyClass.new
obj.mymeth
puts obj.login_method
Fran Martinez
  • 2,994
  • 2
  • 26
  • 38