Conditional key/value in a ruby hash

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

    From Ruby 1.9+, if you want to build a hash based on conditionals you can use tap, which is my new favourite thing. This breaks it onto multiple lines but is more readable IMHO:

    {}.tap do |my_hash| 
      my_hash[:a] = 'a'
      my_hash[:b] = 'b' if condition
    end
    

提交回复
热议问题