Skip to content

Instantly share code, notes, and snippets.

@dpwright
Last active August 29, 2015 14:01
Show Gist options
  • Save dpwright/dbe64e383fad50fb1e94 to your computer and use it in GitHub Desktop.
Save dpwright/dbe64e383fad50fb1e94 to your computer and use it in GitHub Desktop.
Functional additions to ruby "array"
# Threw together these two functions to demonstrate adding some immutable modification
# functions to Ruby's Array class. "update" takes a hash of indices to values and
# returns a new array with the appropriate indices replaced by the supplied values.
# "modify" takes a list of indices and runs the block on those indices that match;
# like a version of "map" where you can specify the indices.
# Maybe you can already do this in Ruby, but I couldn't see anything in the docs so
# here's my hacky little monkey patch...
class Array
def update(replacements)
each_with_index.map{ |x, i| replacements.include?(i) ? replacements[i] : x }.to_a
end
def modify(indices)
each_with_index.map{ |x, i| indices.include?(i) ? yield(x) : x }.to_a
end
end
# [1, 2, 3, 4].update(2 => 'a')
# => [1, 2, "a", 4]
# [1, 2, 3, 4].modify [2] { |x| x = x + 1 }
# => [1, 2, 4, 4]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment