在Rails项目上,我收集了一个带有10-15个键值对的散列,并将它传递给一个类(服务对象)进行实例化。除非没有值(或nil
),否则应从哈希中的值设置对象属性。在这种情况下,该属性将被理想地设置为默认值。将`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 + +
感谢格式帮助泽 – phpete