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

后端 未结 4 1706
野性不改
野性不改 2021-01-12 19:22

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

~: irb
>> puts \"foo\"
foo
=> nil
>         


        
相关标签:
4条回答
  • 2021-01-12 19:37

    Because that's the definition of privacy in Ruby: private methods can only be called with an implicit receiver.

    Actually, there's an exception to this rule: because foo = bar always creates a local variable, you are allowed to call private setters like self.foo = bar, because otherwise you wouldn't be able to call them at all (without using reflection).

    0 讨论(0)
  • 2021-01-12 19:46

    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.

    0 讨论(0)
  • 2021-01-12 19:49

    You're correct that self is the implied receiver when you don't specify one explicitly. The reason that you're not allowed to do self.puts is that you may not call private methods with an explicit receiver (even if that receiver is self) and as the error message says, puts is a private method.

    0 讨论(0)
  • 2021-01-12 19:55

    You can't access private methods in ruby using the self. syntax, or generally speaking using any receiver (something in front of the .). That is only possible for protected methods.

    0 讨论(0)
提交回复
热议问题