Skip to content

Instantly share code, notes, and snippets.

@karatedog
Created August 24, 2012 15:44
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save karatedog/3452159 to your computer and use it in GitHub Desktop.
Save karatedog/3452159 to your computer and use it in GitHub Desktop.
Ruby Array's subtract method which subtracts the values of the elements not the elements themselves
# Ruby Array's "-" (minus) method removes elements from the receiver which exist in the parameter Array
[5, 6, 1] - [2, 3, 5]
# => [6, 1]
# this #subtract method will subtract the value of the parameter Array from the value of the receiver Array, defined by the actual index.
# type mismatch, Nil, and different Array length are not handled
class Array
def subtract(other_ary)
self.map.with_index {|v, i| v-other_ary[i]}
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment