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.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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.newa 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.