Skip to content

Instantly share code, notes, and snippets.

@jrab89
Last active August 29, 2015 13:58
Show Gist options
  • Save jrab89/10301058 to your computer and use it in GitHub Desktop.
Save jrab89/10301058 to your computer and use it in GitHub Desktop.
Change values in a hash without modifying the origional?
arr = [{num: 1}, {num: 2}, {num: 3}]
arr.map{|h| h[:num] += 1; h} # [{:num=>2}, {:num=>3}, {:num=>4}]
arr # [{:num=>2}, {:num=>3}, {:num=>4}]
# is there a better way to do this?
arr = [{num: 1}, {num: 2}, {num: 3}]
arr.map{|h| clone = h.clone; clone[:num] += 1; clone} # [{:num=>2}, {:num=>3}, {:num=>4}]
arr # [{num: 1}, {num: 2}, {num: 3}]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment