Skip to content

Instantly share code, notes, and snippets.

@epidemian
Created February 2, 2015 03:58
Show Gist options
  • Save epidemian/45f64a77379ee235aaae to your computer and use it in GitHub Desktop.
Save epidemian/45f64a77379ee235aaae to your computer and use it in GitHub Desktop.
class Mapper < BasicObject
def initialize(enumerable)
@enumerable = enumerable
end
def method_missing(*args, &block)
@enumerable.map { |o| o.public_send(*args, &block) }
end
end
module Enumerable
def mapper
Mapper.new(self)
end
end
# Similar to .map(&:method) when using no arguments:
[2, -5, 7, -42].mapper.abs # => [2, 5, 7, 42]
# But it can also receive arguments:
%w(hello world).mapper.count('l') # => [2, 1]
# And even blocks!
[1..5, 6..10].mapper.select(&:even?) # => [[2, 4], [6, 8, 10]]
# It can be used to do some weird stuff:
(1..4).mapper ** 2 # => [1, 4, 9, 16]
%w(Ruby is weird).mapper + '!' # => ["Ruby!", "is!", "weird!"]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment