使用关键字参数
你可以通过在方法定义中指定名称来定义方法中的关键字参数:
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