Building a hash in a conditional way

后端 未结 11 831
梦如初夏
梦如初夏 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:10

    In case you want to add few keys under single condition, you can use merge:

    hash = {
      :key1 => value1,
      :key2 => value2,
      :key3 => value3
    }
    
    if condition
      hash.merge!(
        :key5 => value4,
        :key5 => value5,
        :key6 => value6
      )
    end
    
    hash
    
    0 讨论(0)
  • 2021-02-01 02:14

    Keep it simple:

    hash = {
      key1: value1,
      key3: value3,
    }
    
    hash[:key2] = value2 if condition
    

    This way you also visually separate your special case, which might get unnoticed if it is buried within hash literal assignment.

    0 讨论(0)
  • 2021-02-01 02:17

    I use merge and the ternary operator for that situation,

    hash = {
      :key1 => value1,
      :key3 => value3,
      ...
    }.merge(condition ? {:key2 => value2} : {})
    
    0 讨论(0)
  • 2021-02-01 02:18

    Simple as this:

    hash = {
      :key1 => value1,
      **(condition ? {key2: value2} : {})
    }
    

    Hope it helps!

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题