Initializing hashes

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

    The constructor of Hash, in its first argument, have a default value for the keys. This way

    >> a_hash = Hash.new "first text"
    => {}
    >> a_hash['a']
    => "first text"
    >> a_hash['b'] += ", edit"
    => "first text, edit"
    

提交回复
热议问题