Ruby

Rubyのキーワード引数とオプション引数の組み合わせの注意点

キーワード引数

def self.print(message: "Hi")
  puts message
end

print #=> Hi
print(message: "VietNam") #=> VietNam

オプション引数

def self.print(**message)
  puts message
end

print(greeting: "Hi") #=> {:greeting => 'Hi'}
print(greeting: "Hi", country: "VietNam") #=> {:greeting => 'Hi', :country => "VietNam"}

キーワード引数とオプション引数の組み合わせ

def self.print(greeting: "Hi", **option)
  puts "#{greeting}, #{option}"
end

print(country: "VietNam") #=> Hi, {:country => "VietNam"}
print(greeting: "Hello",country: "VietNam") #=> Hello, {:country => "VietNam"}
option = {country: "VietNam"}
print(option)  #=> Hi, {:country => "VietNam"}

print(greeting: "Hello", option) #=> Syntax Error
#原因: print(greeting: "Hello", option) => print(greeting: "Hello", {country: "VietNam"})

print(greeting: "Hello", **option) #=> Hello, {:country => "VietNam"}
#原因: print(greeting: "Hello", **option) => print(greeting: "Hello", country: "VietNam")