Hommer Smith
Hommer Smith

Reputation: 27852

Calling self.private_method in Ruby not throwing error?

I thought that when calling a private method it was unacceptable to place a explicit receiver. Well I did this in Ruby 2.0 and I can get results:

class Test
  def public_method
    self.set_size=10
  end

  def return_size
    @size
  end

  private

  def set_size=(size)
    @size = size
  end

 end

test = Test.new
test.public_method
p test.return_size

Why is this?

Upvotes: 2

Views: 57

Answers (2)

Jörg W Mittag
Jörg W Mittag

Reputation: 369468

Private setters can be called with an explicit receiver of self. In fact, they have to be called with an explicit receiver, because otherwise they couldn't be called at all, since

foo = bar

is an assignment to a local variable, not a method call.

Upvotes: 2

Nobita
Nobita

Reputation: 23713

You are right except on one thing...setters (def method=) can be called with an explicit receiver of self, so that you can call private setters.

So, actually if you were about to do this:

class Test
  def public_method
    self.say_hi
  end

  def return_size
    @size
  end

  private

  def say_hi
    puts "oh hay there"
  end

 end
test = Test.new
test.public_method
test.return_size

It would throw a private method say_hi called for..

Upvotes: 0

Related Questions