簡體   English   中英

根據條件在哈希中添加密鑰

[英]add key in hash based on condition

我有以下方法

def some_method
   ...do something here...

    @customer_info = {
      a: a,
      b: b
    }
end

如果變量customertrue ,我想在@customer_info中添加鍵c,例如,

@customer_info = {
  a: a,
  b: b,
  c: something if customer is true
}

試圖做這樣的事情,但沒有運氣

@customer_info.merge(customer.present? {c: something} : {})
@customer_info[:c] = something if customer

也許您只是想念? 在您的三元運算符中?

您的方法似乎在控制台中對我有用:

> 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?

評論員很好地解釋了原因。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM