Building a hash in a conditional way

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

提交回复
热议问题