B
B
Bogdan2018-06-13 16:37:37
Ruby on Rails
Bogdan, 2018-06-13 16:37:37

Calling private methods?

Hello. Please tell me, there's something I can't figure out. Does the private write method work fine, but does the private read method throw an error?

test.rb:8:in `read': private method `session_lang' called for #<Tst:0x000000000302e4e8>

class Tst

  def write
    self.session_lang = 'ru'
  end

  def read
    self.session_lang
  end

  private

  def session_lang
    p 'read'
  end

  def session_lang= (value)
    p 'write'
  end
end

tst = Tst.new
tst.write
tst.read

If you call the read method for the method without self, then it works
def read
    self.session_lang
  end

If you call a method for writing without self, then it is not the method that is called, but simply the value is assigned to the variable
def write
    session_lang = 'ru'
  end

Just in a real case, I have something like that, but when the methods are private, then the error
def write
    self.session_lang ||= 'ru'
  end

Thank you.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
Z
Zaporozhchenko Oleg, 2018-06-14
@bogdan_uman

because you call a public method on an object, but it doesn't exist. It doesn't matter that self and the current object are the same. Ruby sees the syntax for calling a public method, calls it and does not find it, says that there is the same, but private.

A
Andrey Andreev, 2018-06-13
@b0nn1e

It is normal behavior that write methods require self.
Precisely for the fact that such garbage as you did not exist.
But since they are called via self, private methods are not available.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question