[英]Can I put some form of If..End blocks inside of a hash definition?
我正在創建一個Web應用程序以與Chargify集成。 我想回到同一個哈希customer_id
組如果用戶擁有與賬戶相關聯的客戶,並customer_attributes
如果客戶有被創建。
有什么辦法可以對哈希定義中的if..end塊執行此操作。 例如,我想要做類似以下的事情(不起作用):
def subscription_params(product_id)
{
:product_id => product_id,
if customer_id.nil?
:customer_attributes => customer_params,
else
:customer_id => customer_id,
end
:credit_card_attributes => credit_card_params
}
end
使用Hash.merge
有條件地合並一組(或另一組)鍵值對:
def subscription_params(product_id)
{
:product_id => product_id,
:credit_card_attributes => credit_card_params
}.merge(customer_id.nil? ?
{ :customer_attributes => customer_params } :
{ :customer_id => customer_id }
)
end
嘗試過三元運算符?
雖然可以使用:key => if bool then val1 else val2 end
來指定單個值 ,但是無法使用if語句來選擇是否在文字哈希中插入鍵值對。
話雖如此,您可以使用Ruby 1.8.7和Ruby 1.9+中經常被忽略的Object#tap
方法有條件地將值插入哈希:
irb(main):006:0> { :a => "A"}.tap { |h| if true then h[:b] = "B" end }.tap { |h| if false then h[:c] = "D" end }
=> {:b=>"B", :a=>"A"}
慣用的方法是利用哈希中的默認nil值。
> myHash = {:x => :y} # => {:x=>:y}
> myHash[:d] # => nil
因此,您可以設置:customer_id
或:customer_attributes
,無需if語句,然后再測試存在哪個語句。 執行此操作時,您可能會首選:customer_id
。
unless purchase[:customer_id].nil?
@customer = Customer.find(purchase[:customer_id])
else
@customer = Customer.create!(purchase[:customer_attributes])
end
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.