A
A
Anton Ivanov2016-12-09 09:37:17
Ruby on Rails
Anton Ivanov, 2016-12-09 09:37:17

What is the difference between calling self.method and just method from a class instance in ruby?

Hello.
A private method is defined in a class. method
If I call it from a public method of an instance of the same class as self.method, then I get an error (Private method `method' called ). If I write simply method, then everything works.
Logically, I see that self.method calls this method "outside" the class, but I would like to read the documentation. Didn't find it by searching.
Code example:

class Entity
    def do_something
       private_method
    end

    def do_something2
        self.private_method
    end

    private
    def private_method
        puts 'works'
    end
end

entity = Entity.new
entity.do_something
entity.do_something2

conclusion:
works
1.rb:7:in `do_something2': private method `private_method' called for #<Entity:0x007f93c0003358> (NoMethodError)
Did you mean?  private_methods
  from 1.rb:18:in `<main>'

Thanks in advance.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anna Buyanova, 2016-12-09
@Fly3110

Yes, a private method cannot be called through an explicit call to the class, even if it is self.
> A private method cannot be called with an explicit receiver at all, even if that receiver is “self”.
https://en.wikibooks.org/wiki/Ruby_Programming/Syn...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question