List Comprehensions In Ruby
Join the DZone community and get the full member experience.
Join For FreeTaken from: http://www.ruby-forum.com/topic/89416
Author: Phrogz
To avoid reinventing the wheel check out the built-in methods described in:
http://www.ruby-doc.org/core/classes/Array.html and
http://www.ruby-doc.org/core/classes/Enumerable.html.
#class Array
module Enumerable
def comprehend(&block)
block ? map(&block).compact : self
end
end
old_data = *(1..5) # alternatives to the splat operator: (1..5).to_a or (1..5).collect
new_data = *(3..9)
# some reinventing going on here ...
added = new_data.comprehend { |x| x if not old_data.include?(x) }
removed = old_data.comprehend { |x| x if not new_data.include?(x) }
same = new_data.comprehend { |x| x if old_data.include?(x) }
modified = new_data.comprehend { |x| x**2 if not x % 2 == 0 }
p added #=> [6, 7, 8, 9]
p added = new_data - old_data #=> [6, 7, 8, 9]
p removed #=> [1, 2]
p removed = old_data - new_data #=> [1, 2]
p same #=> [3, 4, 5]
p same = old_data & new_data #=> [3, 4, 5]
p modified #=> [9, 25, 49, 81]
new_data = [[5, 9], [22, 3], [99, 564]]
bool_vals = new_data.comprehend { |x, y| x <= y }
p bool_vals #=> [true, false, true]
Opinions expressed by DZone contributors are their own.
Comments