[Ruby] Specify the argument name of the method. Meaning of the colon (:) at the end

This is a personal memo.

About the meaning of the description that the variable with a colon after it is specified in the argument of the method.

** ▼ This kind of ** def jadge(x:)

python


def jadge(x:)
  p "exist x" if x.present?
end

The meaning of the colon after the argument

The colon at the end of the argument specifies ** a variable name **. (Called ** keyword argument **)

Normally, the arguments are assigned to the first argument, the second argument ,,, in the order in which they are passed, but if you add a colon at the end, you can pass the value of the argument that matches the variable name.

Especially when there are multiple variables to handle, it is convenient because you can specify them by variable name.

Specify the variable name with a colon


#Function definition
def jadge(x:, y:)
  p "exist x" if x.present?
  p "exist y" if y.present?
end


#Function execution
jadge(y: false, x: true)
=> "exist x"

** ▼ Normal **

python


def jadge(x, y)
  p "exist x" if x.present?
  p "exist y" if y.present?
end

y = false
x = true
jadge(y, x)
=> "exist y"

The values ​​are entered in the order in which they were passed, not the variable names.

Recommended Posts

[Ruby] Specify the argument name of the method. Meaning of the colon (:) at the end
[Ruby] Insert, replace, destroy at the end of the character string [b021]
Call a method of the parent class by explicitly specifying the name in Ruby
[Kotlin] Get the argument name of the constructor by reflection
definition of ruby method
Ruby, Nokogiri: Get the element name of the selected node
How to specify an array in the return value / argument of the method in the CORBA IDL file
[Ruby] Questions and verification about the number of method arguments
[ruby] Method call with argument
About the behavior of ruby Hash # ==
About the role of the initialize method
[Ruby] Display the contents of variables
[Rails] Regarding the presence or absence of parentheses in the argument of the render method
Iterative processing of Ruby using each method (find the sum from 1 to 10)
[Ruby] Let's examine the inheritance tree while watching the flow of method search