Skip to content

Instantly share code, notes, and snippets.

@ono
Created November 9, 2010 14:54
Show Gist options
  • Save ono/669183 to your computer and use it in GitHub Desktop.
Save ono/669183 to your computer and use it in GitHub Desktop.
module Maybe
def wrap_block(block)
lambda do |a|
a==nil ? nil : block.call(a)
end
end
end
module MaybeNumeric
def wrap_block(block)
lambda do |a|
block.call(a.is_a?(Numeric) ? a : 0)
end
end
end
module Underscore
def method_missing(sym,*args,&block)
if sym.to_s =~ /^_(.+)/ && respond_to?($1) && respond_to?(:wrap_block)
send($1.to_sym,*args,&wrap_block(block))
else
super
end
end
end
Object.send :include, Underscore
[1,2,nil].map{|x| x * 2} #=> NoMethodError
src = [1,2,nil]
src.extend Maybe
src._map{|x| x * 2} #=> [2, 4, nil]
src = [1,2,nil]
src.extend MaybeNumeric
src._map{|x| x * 2} #=> [2, 4, 0]
src << "abc"
src._map{|x| x * 2} #=> [2, 4, 0, 0]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment