20
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Ruby 2.7 で private メソッドが self. 付きで呼び出せるようになる

20
Posted at

ブログ記事からの転載です。

Ruby 2.7 で private メソッドが self. 付きで呼び出せるようになる予定です。

Ruby 2.6

class X
  def hoge
    # Error
    # private method `value' called for #<X:0x0000561963d99e78 @value=42> (NoMethodError)
    self.value
  end

  private

  def value
    42
  end
end

Ruby 2.7

class X
  def hoge
    # OK
    self.value
  end

  private

  def value
    42
  end
end

もちろん self. 以外のレシーバで呼び出した場合は依然としてエラーになります。

class X
  private

  def value
    42
  end
end

# Error
# private method `value' called for #<X:0x0000561963d99e78 @value=42> (NoMethodError)
p X.new.value

個人的にはそこまで必須ではないんですが、変数名と同じ名前の private メソッドを呼びたい場合に便利かなあって感じですかねえ。
あとは self.value = 42 ってかけるのに self.value ってかけないのはなんか統一感がない気はしていたのでそういう意味ではいいんじゃないですかねー。

20
6
5

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
20
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?