Ruby 2.7.0 Allows To Call Private Methods With self
September 07, 2020
Before Ruby 2.7.0, we were able to call private attr_writer
method using self
but were getting an error while calling a private attr_reader
method and any other private method.
Let's see an example:
class Player
def initialize
self.name = "Roger Federer"
puts self.name
puts self.game
end
private
attr_accessor :name
def game
"Tennis"
end
end
# Ruby 2.6.6
Player.new
#=> in `initialize': private method `name' called for
#=> #<Player:0x00007fefbf8246d0 @name="Roger Federer"> (NoMethodError)
# If we fix the above error, then we will get following error
#=> in `initialize': private method `game' called for
#=> #<Player:0x00007fd62f05f570 @name="Roger Federer"> (NoMethodError)
Before Ruby 2.7.0, the above example would throw an error to notify that we can't call private methods name
and game
.
However, in the above example we have called the writer method name=()
using self.name=
and that line of code does not throw any error.
Finally, this inconsistent behavior has been fixed in Ruby 2.7.0 and we can execute the above example without getting any error.
# Ruby 2.7.0
Player.new
#=> Roger Federer
#=> Tennis
Share feedback with us at:
info@scriptday.com