Initializing hashes

后端 未结 5 1492
傲寒
傲寒 2021-02-07 10:25

I frequently write something like this:

a_hash[\'x\'] ? a_hash[\'x\'] += \' some more text\' : a_hash[\'x\'] = \'first text\'

There ought to be

5条回答
  •  北荒
    北荒 (楼主)
    2021-02-07 10:54

    Since you are using the hash to collect strings, I assume you simply want to make sure that you don't get an error when appending. Therefore, I'd make the hash default the empty string. Then you can append without error, no matter the hash key.

    a_hash = Hash.new {|h,k| h[k]=""}
    
    texts = ['first text', ' some more text']
    
    texts.each do |text|
      a_hash['x'] << text
    end
    
    puts a_hash['x'] #=> 'first text some more text'
    

提交回复
热议问题