Skip to content

Instantly share code, notes, and snippets.

@jamesarosen
Created August 5, 2013 02:30
Show Gist options
  • Select an option

  • Save jamesarosen/6153074 to your computer and use it in GitHub Desktop.

Select an option

Save jamesarosen/6153074 to your computer and use it in GitHub Desktop.
Shovel Out, Elixir-Inspired Irresponsible Programming in Ruby
Object.class_eval do
def >>(callable = nil, &block)
raise ArgumentError.new('>> takes a callable or block') unless callable.nil? ^ block.nil?
(callable || block).call self
end
end
Enumerable.class_eval do
def >>(callable = nil, &block)
raise ArgumentError.new('>> takes a callable or block') unless callable.nil? ^ block.nil?
map &(callable || block)
end
end
[ Fixnum, Bignum, Process::Status ].each do |klass|
klass.class_eval do
original_shovel_out = instance_method(:>>)
define_method :>> do |*args|
raise ArgumentError.new("#{klass}#>> takes an Integer, callable, or block") unless block_given? || args.length == 1
return yield(self) if block_given?
arg = args[0]
return original_shovel_out.bind(self).call(arg) if arg.respond_to?(:to_i)
callable.call self
end
end
end
double = lambda { |x| x * 2 }
'hello' >> double # 'hellohello'
12 >> double # 24
[5, 6, 2] >> double # [10, 12, 4]
@jamesarosen
Copy link
Copy Markdown
Author

Thanks, @josevalim, for inspiring me with |>
Thanks, @steveklabnik, for recommending Irresponsible Programming :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment