Skip to content

Instantly share code, notes, and snippets.

@JunichiIto
Last active March 29, 2018 12:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JunichiIto/4b4d224fcfa5c78bb060aa64c1209a64 to your computer and use it in GitHub Desktop.
Save JunichiIto/4b4d224fcfa5c78bb060aa64c1209a64 to your computer and use it in GitHub Desktop.
Question and answer about プロを目指す人のためのRuby入門

Q.

p250で、クラスメソッドをprivateにしたい場合とありますが、privateメソッドは「レシーバを指定して呼び出すことができない」とあるので不思議です。 User.hello のUserはレシーバとは呼ばないのかということです。

https://twitter.com/maehrm/status/979326471075278848

A.

いいえ、Userはレシーバです。なので、クラスメソッドのhelloがprivateメソッドだった場合は、User.helloのようにレシーバを指定して呼び出すとエラーになります。

となると、「このhelloメソッドはいつ誰がどうやって呼び出すの?」という疑問が出てくるかもしれません。この場合、クラスの外からは呼び出せませんが、クラスの中であれば呼び出せます。 つまり、他のクラスメソッドがhelloメソッドを呼び出すケースが考えられます。

たとえば以下のような感じです。

class User
  class << self
    def greet
      # クラスメソッドのgreetから、privateなクラスメソッドであるhelloを呼び出す
      "#{hello} I am User class."
    end
    
    private
    
    def hello
      'Hello!'
    end
  end
end
User.greet #=> "Hello! I am User class."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment