LoginSignup
1
0

More than 5 years have passed since last update.

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

Last updated at Posted at 2018-07-12

キーワード引数

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")
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0