Conditional key/value in a ruby hash

后端 未结 12 1093
天命终不由人
天命终不由人 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条回答
  •  天命终不由人
    2020-12-24 05:31

    In Ruby 2.0 there is a double-splat operator (**) for hashes (and keyword parameters) by analogy to the old splat operator (*) for arrays (and positional parameters). So you could say:

    {a: 'b', **(condition ? {b: 'b'} : {})}
    

提交回复
热议问题