I frequently write something like this:
a_hash['x'] ? a_hash['x'] += ' some more text' : a_hash['x'] = 'first text'
There ought to be a better way to do this, but I can't find it.
I frequently write something like this:
a_hash['x'] ? a_hash['x'] += ' some more text' : a_hash['x'] = 'first text'
There ought to be a better way to do this, but I can't find it.
There are two ways to create initial values with for a
Hash
.One is to pass a single object in to
Hash.new
. This works well in many situations, especially if the object is a frozen value, but if the object has internal state, this may have unexpected side-effects. Since the same object is shared between all keys without an assigned value, modifying the internal state for one will show up in all.Another initialization method is to pass
Hash.new
a block, which is invoked each time a value is requested for a key that has no value. This allows you to use a distinct value for each key.The block is passed two arguments: the hash being asked for a value, and the key used. This gives you the option of assigning a value for that key, so that the same object will be presented each time a particular key is given.
This last method is the one I most often use. It's also useful for caching the result of an expensive calculation.
In case you do not want to mess with the
default=
value (existing hash), you can shorten your code by usingfetch(key [, default])
as a look-up with a default value: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.
You can specify the initial value when you create your hash:
The constructor of Hash, in its first argument, have a default value for the keys. This way