Skip to content

Instantly share code, notes, and snippets.

@houshuang
Created October 17, 2013 23:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save houshuang/7034026 to your computer and use it in GitHub Desktop.
Save houshuang/7034026 to your computer and use it in GitHub Desktop.
utility function for R to make it easier to add to a hash value without checking whether it exists first
class Object
def add_safe(var,val)
if val.class == Fixnum
if self[var].nil?
self[var] = val
else
self[var] = self[var] + val
end
else
if self[var].nil?
self[var] = [val]
else
self[var] = self[var] + [val]
end
end
end
end
class Hash
def add_safe(var,val)
super
end
alias :add :add_safe # we've already used this in the code
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment