LoginSignup
2
2

More than 3 years have passed since last update.

Rubyの細かい文法: 同名の変数とメソッドがある場合

Last updated at Posted at 2020-09-11

※ 09/12 コメントの指摘を受けて書き足し。

Ruby では変数とメソッドに同じ名前をつけられます。同名の変数とメソッドがある場合、変数のほうが優先されます。定義の順序とは関係ありません。

() を付ければ、メソッドと見なされます。引数を指定しても、メソッド呼び出しになります。

def foo(n = 1)
  "method" * n
end

foo = "variable"

# これは変数
foo #=> "variable"
# これはメソッド呼び出し
foo() #=> "method"
# これもメソッド呼び出し
foo 2 #=> "methodmethod"

. を付けてレシーバを指定したときも、メソッドと見なされます。

public  # Ruby 2.6まで: private だと . で呼び出せない / 2.7以降: publicなしでもOK
def foo(n = 1)
  "method" * n
end

foo = "variable"

# これは変数
foo #=> "variable"
# これはメソッド呼び出し
self.foo #=> "method"

Rubyのクラス名は定数名、つまり変数の一種なので、同じ名前のクラスとメソッドがあるときは上記と同じ動作になります。

public
def Foo(n = 1)
  "method" * n
end

class Foo
end

# これはクラス
Foo #=> Foo
# これはメソッド呼び出し
Foo() #=> "method"
# これもメソッド呼び出し
Foo 2 #=> "methodmethod"
# これもメソッド呼び出し
self.Foo #=> "method"

Kernelモジュール には、ArrayとかStringという名前のメソッドがあります。

# Stringクラスじゃなくて、KernelモジュールのStringメソッドの呼び出し。
String(1) #=> "1"
2
2
4

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
2
2