【发布时间】:2016-06-14 08:22:34
【问题描述】:
在 Rails 项目中,我正在收集一个包含 10-15 个键值对的哈希,并将其传递给一个类(服务对象)以进行实例化。对象属性应该从散列中的值设置,除非没有值(或nil)。在这种情况下,最好将该属性设置为默认值。
我不想在创建对象之前检查哈希中的每个值是否不是nil,而是想找到一种更有效的方法。
我正在尝试使用具有默认值的命名参数。我不知道这是否有意义,但我想在使用nil 调用参数时使用默认值。我为此功能创建了一个测试:
class Taco
def initialize(meat: "steak", cheese: true, salsa: "spicy")
@meat = meat
@cheese = cheese
@salsa = salsa
end
def assemble
"taco with: #@meat + #@cheese + #@salsa"
end
end
options1 = {:meat => "chicken", :cheese => false, :salsa => "mild"}
chickenTaco = Taco.new(options1)
puts chickenTaco.assemble
# => taco with: chicken + false + mild
options2 = {}
defaultTaco = Taco.new(options2)
puts defaultTaco.assemble
# => taco with: steak + true + spicy
options3 = {:meat => "pork", :cheese => nil, :salsa => nil}
invalidTaco = Taco.new(options3)
puts invalidTaco.assemble
# expected => taco with: pork + true + spicy
# actual => taco with: pork + +
【问题讨论】:
-
感谢sawa的格式化帮助
标签: ruby named-parameters