【问题标题】:Can I put some form of If..End blocks inside of a hash definition?我可以在哈希定义中放置某种形式的 If..End 块吗?
【发布时间】:2010-04-06 01:53:38
【问题描述】:

我正在创建一个 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

【问题讨论】:

    标签: ruby arrays hash


    【解决方案1】:

    使用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
    

    【讨论】:

      【解决方案2】:

      尝试过三元运算符?

      【讨论】:

      • 这不起作用,因为值项目的键将根据条件进行更改。
      【解决方案3】:

      虽然您可以使用 :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"}
      

      【讨论】:

      • 它不像 Ruby 1.9 的新手那样被忽视,并且不适用于 1.9 之前的版本。
      • 除非它在 ​​1.8.7 中,就像我上面说的那样。 sfr-fresh.com/unix/misc/ruby-1.8.7-p249.tar.gz:a/…
      • 好的,Ruby 1.8.7 补丁级别 249 :) -- 当然,现在应该可以在 大多数 系统上使用。
      【解决方案4】:

      这样做的惯用方法是利用哈希中的默认 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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-05-24
        • 2016-07-26
        • 2017-09-24
        • 1970-01-01
        • 1970-01-01
        • 2015-07-05
        • 2014-11-09
        • 1970-01-01
        相关资源
        最近更新 更多