Thursday, 19 April 2012

Ruby 1.9.2 Goodies

[1,2,3].each_with_object(1).map(&:+)
# => [2, 3, 4]

# Same outcome, even shorter
[1, 2, 3].map(&1.method(:+))
# => [2, 3, 4]
# Thanks to rubyquicktips.com

######## even in 1.8
a = [[1,2,3],[2,3,4],[3,4,5]]

# get the union:
a.inject(a.first) { |f,x| f = f | x } # => [1, 2, 3, 4, 5]

# get the intersection:
a.inject(a.first) { |f,x| f = f & x } => [3]

No comments:

Post a Comment