Created
August 5, 2013 02:30
-
-
Save jamesarosen/6153074 to your computer and use it in GitHub Desktop.
Shovel Out, Elixir-Inspired Irresponsible Programming in Ruby
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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] |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks, @josevalim, for inspiring me with |>
Thanks, @steveklabnik, for recommending Irresponsible Programming :)