Building a hash in a conditional way

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

提交回复
热议问题