Skip to content

Instantly share code, notes, and snippets.

@mecampbellsoup
Last active December 20, 2015 11:39
Show Gist options
  • Save mecampbellsoup/6125506 to your computer and use it in GitHub Desktop.
Save mecampbellsoup/6125506 to your computer and use it in GitHub Desktop.
better way to effectively iterate one array over another: http://www.ruby-doc.org/core-2.0/Array.html#method-i-26
def sum_of_intersection?(x1, x2, y1, y2)
intersection = (x1..x2).to_a & (y1..y2).to_a
intersection.inject{|sum,i| sum + i}
end
p sum_of_intersection?(5,15,10,20)
@nimitmaru
Copy link

Pretty cool Matt! Love the set intersection operator. One disadvantage to this approach vs how we talked about earlier (where we manually found the intersecting range) is that if one of our ranges were say a billion numbers wide or more, this code would take up a ton of memory due to having to convert the entire range into an array. You can never run out of cool Ruby shortcuts :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment