Skip to content

Instantly share code, notes, and snippets.

@echristopherson
Created February 26, 2011 04:12
Show Gist options
  • Save echristopherson/844931 to your computer and use it in GitHub Desktop.
Save echristopherson/844931 to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby1.9
# Extends Array#map to take symbols, without having to use & on them.
# I can't find any way to define this in Enumerable and then have it
# automatically get picked up by Array et al. Even when I defined this in a
# module (Enumerable or another) and then include it into Array, it doesn't
# seem to recognize the new method.
class Array
alias old_map map
def map(arg=nil)
puts "Calling new map"
if arg.is_a? Symbol
puts "Arg is a symbol"
old_map { |i| arg.to_proc.call i}
else
if block_given?
old_map { |i| yield i }
else
old_map(arg)
end
end
end
end
ary = %W[foo\n bar\n baz\n]
p ary.map(&:chomp)
p ary.map(:chomp)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment