gpt4 book ai didi

ruby - 使用默认命名参数将 `nil` 传递给方法

转载 作者:数据小太阳 更新时间:2023-10-29 09:01:02 24 4
gpt4 key购买 nike

在一个 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 + +

最佳答案

如果你想遵循面向对象的方法,你可以在一个单独的方法中隔离你的默认值,然后使用 Hash#merge:

class Taco
def initialize (args)
args = defaults.merge(args)
@meat = args[:meat]
@cheese = args[:cheese]
@salsa = args[:salsa]
end

def assemble
"taco with: #{@meat} + #{@cheese} + #{@salsa}"
end

def defaults
{meat: 'steak', cheese: true, salsa: 'spicy'}
end
end

然后按照@sawa(谢谢)的建议,使用 Rails 的 Hash#compact 为您的输入散列明确定义 nil 值,您将拥有以下内容输出:

taco with: chicken + false + mild
taco with: steak + true + spicy
taco with: pork + true + spicy

编辑:

如果你不想使用Rails 的精彩的Hash#compact 方法,你可以使用Ruby 的Array#compact 方法。将 initialize 方法中的第一行替换为:

args = defaults.merge(args.map{|k, v| [k,v] if v != nil }.compact.to_h)

关于ruby - 使用默认命名参数将 `nil` 传递给方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35731009/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com