Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If `self` is always the implied receiver in Ruby, why doesn't `self.puts` work?

Tags:

ruby

In Ruby, my understanding is that self is the implied receiver for any bare method call. However:

~: irb
>> puts "foo"
foo
=> nil
>> self.puts "foo"
NoMethodError: private method `puts' called for main:Object

What explains this?

In case it's any help:

>> method(:puts).owner
=> Kernel
like image 730
Nathan Long Avatar asked Jul 24 '12 13:07

Nathan Long


1 Answers

Private methods can't have a receiver

I think the answer is this: Ruby's way of enforcing method privacy is that it doesn't allow calling private methods with an explicit receiver.

An example:

class Baker
  def bake_cake
    make_batter
    self.use_oven # will explode: called with explicit receiver 'self'
  end

  private
  def make_batter
    puts "making batter!"
  end

  def use_oven
    puts "using oven!"
  end

end

b = Baker.new
b.bake_cake

Since there can be no explicit receiver, you certainly can't do b.use_oven. And that is how method privacy is enforced.

like image 176
Nathan Long Avatar answered Sep 28 '22 09:09

Nathan Long