Conditional key/value in a ruby hash

后端 未结 12 1109
天命终不由人
天命终不由人 2020-12-24 04:41

Is there a nice (one line) way of writing a hash in ruby with some entry only there if a condition is fulfilled? I thought of

{:a => \'a\', :b => (\'b\         


        
12条回答
  •  猫巷女王i
    2020-12-24 05:12

    Hash[:a, 'a', *([:b, 'b'] if condition1), *([:c, 'c'] if condition2)]
    

    This relies on the fact that *nil expands to vacuity in ruby 1.9. In ruby 1.8, you might need to do:

    Hash[:a, 'a', *(condition1 ? [:b, 'b'] : []), *(condition2 ? [:c, 'c'] : [])]
    

    or

    Hash[:a, 'a', *([:b, 'b'] if condition1).to_a, *([:c, 'c'] if condition2).to_a]
    

提交回复
热议问题