version ruby 2.6.3 rails 5.2.3
I was addicted to it because I didn't really understand the arguments with keywords. Even though I used equal to define a method with a default value, I was calling an argument with a keyword when calling the method, so an unintended argument was passed and an error occurred. It was.
#Define methods with default valued arguments
def hello(lang = "ja", place = "Japan")
puts "#{lang} : #{place}"
end
#How to call arguments with keywords
hello(lang: "en", place: "America")
#=>
{:lang=>"en", :place=>"America"} : Japan
The argument was interpreted as a hash and an unintended argument was passed.
Reference https://qiita.com/jnchito/items/74e0930c54df90f9704c
def hello(lang: "ja", place: "Japan")
puts "#{lang} : #{place}"
end
#Call with no arguments
hello
#=>
ja : Japan
#Call by changing the argument value with keywords
hello(lang: "en", place: "America")
#=>
en : America
#Call with non-keyword arguments
hello("en", "America")
#=>
wrong number of arguments (given 2, expected 0)
Calling a method with keyworded arguments without arguments calls the method with default values. An error occurs if you try to call it with a keywordless argument.
Reference https://rooter.jp/programming/ruby_method_default/
def hello(lang = "ja", place = "Japan")
puts "#{lang} : #{place}"
end
#Call with no arguments
hello
#=>
"ja : Japan"
#Call with non-keyword arguments
hello("en", "America")
#=>
en : America
Recommended Posts