Normally, if you have a private method, you can’t call it with an explicit receiver, even if that receiver is self
. So you can’t say
def foo
self.bar # explicit receiver
end
private
def bar
123
end
Instead, foo
needs to call simply bar
, leaving the self
implicit:
def foo
bar # implicit receiver
end
However, when you call setters, you always need an explicit receiver, or you’ll just assign a local variable:
def assign_things
self.a = 123
b = 456
end
def a=(v)
puts "This one gets called."
end
def b=(v)
raise "This one never does; the other method makes a local called `b` instead."
end
So, what do you do if you have a private setter? You call it with an explicit receiver:
def assign_things
self.a = 123
end
private
def a=(v)
puts "This is called successfully."
end
There’s a crazy special exception in Ruby that lets you use an explicit receiver of self
with a setter just so that you can call private setters.
This strikes me as weird. Why can’t you call any private method explicitly on self? I thought it was just easier to implement Ruby if you couldn’t, but if they made it work for setters, I’m not sure what the big deal is.
About the Author