Conditional key/value in a ruby hash

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

    This one is nice for multiple conditionals.

    (
      hash = {:a => 'a'}.tap {|h|
        h.store( *[(:b if condition_b), 'b'] )
        h.store( *[(:c if condition_c), 'c'] )
      }
    ).delete(nil)
    

    Note that I chose nil as the "garbage" key, which gets deleted when you're done. If you ever need to store a real value with a nil key, just change the store conditionals to something like:

    (condition_b ? :b : garbage_key)
    

    then delete(garbage_key) at the end.

    This solution will also keep existing nil values intact, e.g. if you had :a => nil in the original hash, it won't be deleted.

提交回复
热议问题