Created
February 2, 2015 03:58
-
-
Save epidemian/45f64a77379ee235aaae to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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