Ruby's fine syntax: if you have variables and methods with the same name

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

Ruby's fine syntax: if you have variables and methods with the same name
[Head panic] Priority when variables / methods with the same name are used in inherited classes
Rails' Private methods hurt if you feel the same as Java!
If you have trouble with the character code problem in Myanmar (Burmese)
If you have trouble with JPA or Hibernate, don't google and look here first
What to do if you cannot execute with the command "Java package name / class name"
Ruby variables and methods
Ruby / rexml: Turn each with an element with the same name