In Ruby, variables and methods can have the same name. If there are variables and methods with the same name, the variable takes precedence. It has nothing to do with the order of definitions.
If you add ()
, it is considered as a method. Even if you specify an argument, it will be a method call.
def foo(n = 1)
"method" * n
end
foo = "variable"
#This is a variable
foo #=> "variable"
#This is a method call
foo() #=> "method"
#This is also a method call
foo 2 #=> "methodmethod"
If you specify a receiver with .
, it is also considered a method.
public # Ruby 2.Up to 6:If it's private.Can't be called with/ 2.7 or later:OK without public
def foo(n = 1)
"method" * n
end
foo = "variable"
#This is a variable
foo #=> "variable"
#This is a method call
self.foo #=> "method"
A Ruby class name is a constant name, that is, a type of variable, so if there are classes and methods with the same name, the behavior will be the same as above.
public
def Foo(n = 1)
"method" * n
end
class Foo
end
#This is a class
Foo #=> Foo
#This is a method call
Foo() #=> "method"
#This is also a method call
Foo 2 #=> "methodmethod"
#This is also a method call
self.Foo #=> "method"
The Kernel Module (https://ruby-doc.org/core-2.7.1/Kernel.html) has methods named Array and String.
#Call the String method of the Kernel module, not the String class.
String(1) #=> "1"
Recommended Posts