Building a hash in a conditional way

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

    A functional approach:

    hash = {
      :key1 => 1,
      :key2 => (2 if condition),
      :key3 => 3,
    }.compact 
    

    If Hash.compact is not available in your environment, write .reject { |k, v| v.nil? }

提交回复
热议问题