使用關鍵字引數

你可以通過在方法定義中指定名稱來定義方法中的關鍵字引數:

def say(message: "Hello World")
  puts message
end

say
# => "Hello World"

say message: "Today is Monday"
# => "Today is Monday"

你可以定義多個關鍵字引數,定義順序無關緊要:

def say(message: "Hello World", before: "<p>", after: "</p>")
  puts "#{before}#{message}#{after}"
end

say
# => "<p>Hello World</p>"

say message: "Today is Monday"
# => "<p>Today is Monday</p>"

say after: "</p><hr>", message: "Today is Monday"
# => "<p>Today is Monday</p><hr>"

關鍵字引數可以與位置引數混合使用:

def say(message, before: "<p>", after: "</p>")
  puts "#{before}#{message}#{after}"
end

say "Hello World", before: "<span>", after: "</span>"
# => "<span>Hello World</span>"

在 Ruby 2.1 之前將關鍵字引數與位置引數混合是一種非常常見的方法,因為無法定義必需的關鍵字引數

此外,在 Ruby <2.0 中,在方法定義的末尾新增 Hash 以用於可選引數是很常見的。語法與關鍵字引數非常相似,通過 Hash 的可選引數與 Ruby 2 關鍵字引數相容。

def say(message, options = {})
  before = option.fetch(:before, "<p>")
  after  = option.fetch(:after, "</p>")
  puts "#{before}#{message}#{after}"
end

# The method call is syntactically equivalent to the keyword argument one
say "Hello World", before: "<span>", after: "</span>"
# => "<span>Hello World</span>"

請注意,嘗試傳遞未定義的關鍵字引數將導致錯誤:

def say(message: "Hello World")
  puts message
end

say foo: "Hello"
# => ArgumentError: unknown keyword: foo