Skip to content

Instantly share code, notes, and snippets.

@jboursiquot
Created December 5, 2012 14:46
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 jboursiquot/4216037 to your computer and use it in GitHub Desktop.
Save jboursiquot/4216037 to your computer and use it in GitHub Desktop.
Adding element to array that may not yet exist
# Given:
hash = {}
(('a'..'z').to_a+('a'..'z').to_a).shuffle.each do |e|
# represent the following two lines as a one-liner
hash[:"#{e}"] ||= []
hash[:"#{e}"] << rand(10)
end
# one-liner for the two-liner above
(hash[e.to_sym] ||= []) << rand(10)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment