gpt4 book ai didi

ruby-on-rails - 如何向 *args 添加散列?

转载 作者:数据小太阳 更新时间:2023-10-29 06:54:00 25 4
gpt4 key购买 nike

如何在 Rails 中有条件地将散列添加到 *args 数组?如果存在,我不想践踏原始值。

例如,我有一个接收数组的方法:

def foo(*args)
# I want to insert {style: 'bar'} into args but only if !style.present?
bar(*args) # do some other stuff
end

我已经开始使用 rails 提供的 extract_options 和 reverse_merge 方法:

def foo(*args)
options = args.extract_options! # remove the option hashes
options.reverse_merge! {style: 'bar'} # modify them
args << options # put them back into the array
bar(*args) # do some other stuff
end

它可以工作,但看起来很冗长而且不是很像 ruby 。我觉得我错过了什么。

最佳答案

是的,#extract_options! 是在 Rails 中执行此操作的方法。如果你想更优雅,你将不得不给它起个别名,或者找到你自己的方式来处理这个需求,或者搜索已经做过的人的 gem。

关于ruby-on-rails - 如何向 *args 添加散列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10965967/

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