ruby - Add something to hash value if key exists? -
i have hash in ruby:
hash = hash.new
it has key value pairs in it, say:
hash[1] = "one" hash[2] = "two"
if hash contains key 2
, want add "bananas" value. if hash doesn't have key 2
, want create new key value pair 2=>"bananas"
.
i know can first checkng whether hash has key 2
using has_key?
, act accordingly. requires if
statement , more 1 line.
so there simple, elegant one-liner achieving this?
this works:
hash[2] = (hash[2] || '') + 'bananas'
if want keys behave way, use "default" feature of ruby's hash:
hash = {} hash.default_proc = proc { '' } hash[2] += 'bananas'
Comments
Post a Comment