On Thu, Jun 26, 2014 at 10:58 AM, Robert K.
[email protected] wrote:
Why would you? bar= is defined.
That’s how ruby responds when you try to call a private method using
the explicit self receiver:
class Foo
def use_bar_explicit_self
self.bar
end
private
def bar
‘bar’
end
end
foo = Foo.new
foo.use_bar_explicit_self
~> -:3:in use_bar_explicit_self': private method
bar’ called for
#Foo:0x007fe9c982cd68 (NoMethodError)
~> from -:13:in `’
This works in exactly the same way when you pass a variable to a method:
class Foo
def use_bar_explicit_self(var)
self.bar(var)
end
private
def bar(var)
‘bar’
end
end
foo = Foo.new
foo.use_bar_explicit_self(:a_var)
~> -:3:in use_bar_explicit_self': private method
bar’ called for
#Foo:0x007fdfea828a30 (NoMethodError)
~> from -:13:in `’
But the same rules don’t seem to follow when using the =
operator
class Foo
def value
@bar
end
def use_bar_explicit_self=(var)
self.bar=(var)
end
private
def bar=(var)
@bar = var
end
end
foo = Foo.new
foo.use_bar_explicit_self = :a_var
foo.value # => :a_var
I’m guessing that the =
operator essentially results in doing a send
to "#{method_name}=
and therefore is bypassing ruby’s usual method
visibility rules.
Btw. 1.9.3 also did not choke with this.
Yep - also 1.8.7 and rubinius 2.2.2 - so I guess this is expected
behaviour. It just surprised me