Initializing hashes

后端 未结 5 1499
傲寒
傲寒 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:37

    In case you do not want to mess with the default= value (existing hash), you can shorten your code by using fetch(key [, default]) as a look-up with a default value:

    a_hash['x'] = a_hash.fetch('x', 'first_text') + ' some more text'
    

提交回复
热议问题