Summary of description about method definition of ruby.
The method definition method is basically similar to python. Ruby does not require ":" at the end of the first line. Need "end" at the end.
It is a keyword argument using ":", and a value can be passed by the argument name.
table of contents
python
def method name
processing
end
└ end required
Method name
└ () Not required * When there is no argument
Method example
def hello
puts "Hello"
end
hello
#output
Hello
python
def method name(Argument name 1,Argument name 2,,)
processing
end
Method name(Argument name 1,Argument name 2,,)
└ Cannot be called without arguments (error) └ Match the number of arguments (error if not matched) └ Argument name can be used only in the defined method (scope)
return value
└ Replace the value with the method.
└ Values are strings, formulas, etc.
python
def method name
return value
end
Return value example
def divide(a,b)
return a/b
end
puts add(10,5)
value=add(10,5)
puts "The division result is#{value}is"
#output
2
The division result is 2
return conditional expression
└ The result of the conditional expression is returned as true / false
Method name? (Argument name)
└ Add "?" To the method that returns the boolean value (true / false).
└ As a convention
Method that returns 0 or more as a boolean value
def positive?(value)
return value > 0
end
puts positive?(10)
puts positive?(-3)
#output
true
false
The processing after return in the method is not executed.
python
def divide(a,b)
return a/b
puts "Divided"
end
divide(10,5)
#output
2
Set a boolean value in the return value of the method and call the method with the conditional expression of the if statement.
python
#Method that returns a boolean value
def discount?(price)
return price >= 1000
end
price=800
if discount?(price)
puts "10%Discount. the price is#{price*0.9}is."
else
puts "after#{1000-price}10 in yen%It is a discount"
end
#output
10 for another 200 yen%It is a discount
Use if statements and return values in methods.
python
#Discount consumption tax over 1000
def total_value(price)
if price >= 1000
return price
end
return 1000*1.1
end
puts "The payment amount is#{total_value(800)}It's a yen"
#output
The payment amount is 880 yen
Specify the value by the name of the argument.
def method name (argument name A :, argument name B: ,,,)
└ Add ":" after the argument name
└ No change in processing
Method name (argument name B: value, argument name A: value ,,,)
└ Match with the argument name defined in the method
└ Add ":" after the argument name
python
def user(name:, age:, gender:, word:)
puts "#{name}Is your age#{age}is"
puts "what is your gender#{gender}is"
puts "The habit is "#{word}"is"
end
user(gender:"male", name:"JoJo", age:"17", word:"Oraora Oraoraoraora")
#output
JoJo is 17 years old"
Gender is male"
The habit is "Oraoraoraoraoraoraora""
Recommended Posts