Conditional key/value in a ruby hash

后端 未结 12 1091
天命终不由人
天命终不由人 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:14

    There's a lot of clever solutions in here, but IMO the simplest and therefore best approach is

    hash = { a: 'a', b: 'b' }
    hash[:c] = 'c' if condition
    

    It goes against the OP's request of doing it in two lines, but really so do the other answers that only appear to be one-liners. Let's face it, this is the most trivial solution and it's easy to read.

提交回复
热议问题