Skip to content

Instantly share code, notes, and snippets.

@dandorman
Created March 13, 2015 23:27
Show Gist options
  • Save dandorman/ee58fbf4ff875033aa59 to your computer and use it in GitHub Desktop.
Save dandorman/ee58fbf4ff875033aa59 to your computer and use it in GitHub Desktop.
A fun li'l Ruby experiment.
module Enumerable
def map_into(callable, *args)
map { |value|
value, args = yield(value, *args) if block_given?
callable.call value, *args
}
end
end
require "uri"
p %w[foo.com bar.com baz.com].map_into method(:URI)
# => [#<URI::Generic:0x007f894a0f8108 URL:foo.com>,
# #<URI::Generic:0x007f894a0d1490 URL:bar.com>,
# #<URI::Generic:0x007f894a0d1080 URL:baz.com>]
p %w[foo bar baz].map_into -> str { str.upcase }
# => ["FOO", "BAR", "BAZ"]
# A class example.
class Foo
def initialize(items)
@items = items
end
def bar
# Just to demonstrate how sometimes I want extra args.
@items.map_into method(:upcased_first_chars), 1
end
private
def upcased_first_chars(str, len)
str.upcase[0, len]
end
end
p Foo.new(%w[foo bar baz]).bar
# => ["F", "B", "B"]
# Block version. Get the lengths of the strings, and square 'em.
# Note that the block should produce _all_ of the args desired by map_into's
# callable argument.
# LMAO that this next line parses as desired.
p %w[a bb ccc].map_into -> n { n ** 2 } { |v| v.length }
# => [1, 4, 9]
# Grab the last character of each string, in a rather Byzantine fashion.
# ROFL at Ruby's amazing parser.
p %w[foo bar baz].map_into -> str, i { str.upcase[-i..-1] }, 1
# => ["O", "R", "Z"]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment