Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # this is the curry implementation:
- class Class
- def curry(method_name, options)
- define_method(options[:as] || "#{method_name}_#{options[:with].gsub(/[^\w]/, '_')}") do |*args|
- if(method(method_name).arity == 0 && options[:with].kind_of?(Proc))
- send(method_name, *args.compact, &options[:with])
- else
- send(method_name, *[options[:with], *args].compact)
- end
- end
- end
- end
- # everything below is just me using it in various ways
- # ----------------------------------------------------
- class Foo
- curry :say, :with => "good"
- curry :say_good, :with => "morning"
- curry :say_good, :with => "after noon"
- curry :say_good, :with => "night"
- def say(*words)
- words.join(' ')
- end
- end
- # using the (chained) curried methods in Foo
- Foo.new.say_good_after_noon("Bob") # => "good after noon Bob"
- class Fixnum
- curry :*, :with => 2, :as => 'double'
- curry :/, :with => 2, :as => 'half'
- curry :-, :with => 1, :as => 'array_index'
- end
- # using the curried methods in Fixnum
- 5.double # => 10
- 100.half # => 50
- %w(foo bar baz)[3.array_index] # => "baz"
- class Array
- curry :join, :with => ', ', :as => :csv
- curry :collect, :with => Proc.new {|x| x.name}, :as => :names
- end
- class String
- curry :split, :with => /\s*,\s*/, :as => :parse_csv
- end
- class Time
- curry :strftime, :with => "%Y-%m-%d %H:%M:%S", :as => "iso9075"
- end
- # easy time formatting around your app
- Time.now.iso9075 # => "2008-04-17 14:11:31"
- # curried methods on Array
- %w(foo bar baz).csv # => "foo, bar, baz"
- # curried methods in String
- "foo, bar, baz".parse_csv # => ["foo", "bar", "baz"]
- # and who hasn't done this: people.collect(&:name).join(', ')
- class Person
- attr_accessor :name
- def initialize(name)
- self.name = name
- end
- end
- people = [Person.new("Rob"), Person.new("Chris"), Person.new("Pat"), Person.new("Jim")]
- # instead of doing the old collect and join directly, we use their curried friends
- people.names.csv # => "Rob, Chris, Pat, Jim"
Add Comment
Please, Sign In to add comment