I love enumerable. I really do. I use the functions it provides with the utmost alacrity. Nothing makes me sadder than seeing a #each used to populate an array. Once you start using them a lot in production systems, you notice a bunch of common patterns.
It is a gem, so just do
gem install enumeradical
then rock the house by requiring it. It sets itself up!
require 'enumeradical'
class MyNumberPresenter
def initialize(number)
@number = number
end
end
[1,2,3].map { |number| MyNumberPresenter.new(number) }
# => [#<MyNumberPresenter:0x0000010086b9c8 @number=1>, #<MyNumberPresenter:0x0000010086b630 @number=2>,
#<MyNumberPresenter:0x0000010086b540 @number=3>]
NO MORE! Use Enumerable#map_to(type)
class MyNumberPresenter
def initialize(number)
@number = number
end
end
[1,2,3].map_to MyNumberPresenter
# => [#<MyNumberPresenter:0x0000010086b9c8 @number=1>, #<MyNumberPresenter:0x0000010086b630 @number=2>,
#<MyNumberPresenter:0x0000010086b540 @number=3>]
I have an array of objects, and I want to map them to the value they give from indexing into another object.
require 'date'
[1,2,3].map { |index| Date::ABBR_DAYNAMES[index] } # => ["Mon", "Tue", "Wed"]
NO MORE! Use Enumerable#map_into
require 'date'
[1,2,3].map_into Date::ABBR_DAYNAMES # => ["Mon", "Tue", "Wed"]
class Converter
def hellos(times)
"hello"*times
end
end
converter = Converter.new
[1,2,3].map { |times| converter.hellos(times) }
# => ["hello", "hellohello", "hellohellohello"]
NO MORE! Use Object#map_over
class Converter
def hellos(times)
"hello"*times
end
end
converter = Converter.new
converter.map_over [1,2,3], :hellos
# => ["hello", "hellohello", "hellohellohello"]
class Thingy
def initialize(foo)
self.foo = foo
end
attr_accessor :foo
end
thingies = [Thingy.new("abc"), Thingy.new("def"), Thingy.new("ghi")]
arry = ["def", "abc", "ghi"]
thingies.sort_like(arry, :foo)
# OR
thingies.sort_like(arry) { |t| t.foo }
YES!!!!! Use it.
MIT. See LICENSE