Building a hash in a conditional way

后端 未结 11 864
梦如初夏
梦如初夏 2021-02-01 01:29

I am using Ruby on Rails 3.0.10 and I would like to build an hash key\\value pairs in a conditional way. That is, I would like to add a key and its related value if a condition

11条回答
  •  庸人自扰
    2021-02-01 02:21

    First build your hash thusly:

    hash = {
      :key1 => value1,
      :key2 => condition ? value2 : :delete_me,
      :key3 => value3
    }
    

    Then do this after building your hash:

    hash.delete_if {|_, v| v == :delete_me}
    

    Unless your hash is frozen or otherwise immutable, this would effectively only keep values that are present.

提交回复
热议问题