我有以下方法
def some_method
...do something here...
@customer_info = {
a: a,
b: b
}
end
如果变量customer
为true
,我想在@customer_info中添加密钥c
等等,
@customer_info = {
a: a,
b: b,
c: something if customer is true
}
试图做这样的事但没有运气
@customer_info.merge(customer.present? {c: something} : {})
答案 0 :(得分:6)
@customer_info[:c] = something if customer
答案 1 :(得分:0)
也许您只是在三元运算符中遗漏了?
?
您的方法似乎在我的控制台中起作用:
> customer_info = {a: :a, b: :b}
=> {:a=>:a, :b=>:b}
> c = false
=> false
> customer_info.merge(c ? {c: c} : {})
=> {:a=>:a, :b=>:b}
> c = true
=> true
> customer_info.merge(c ? {c: c} : {})
=> {:a=>:a, :b=>:b, :c=>true}
所以,这个:
@customer_info.merge(customer.present? {c: something} : {})
应该更像是:
@customer_info.merge(customer.present? ? {c: something} : {})
快速更新
正如评论中所指出的,这应该更像是:
@customer_info.merge!({c: something}) if customer.present?
评论员很好地解释了原因。