Guest User

Untitled

a guest
Apr 20th, 2018
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.01 KB | None | 0 0
  1. # this is the curry implementation:
  2. class Class
  3. def curry(method_name, options)
  4. define_method(options[:as] || "#{method_name}_#{options[:with].gsub(/[^\w]/, '_')}") do |*args|
  5. if(method(method_name).arity == 0 && options[:with].kind_of?(Proc))
  6. send(method_name, *args.compact, &options[:with])
  7. else
  8. send(method_name, *[options[:with], *args].compact)
  9. end
  10. end
  11. end
  12. end
  13.  
  14. # everything below is just me using it in various ways
  15. # ----------------------------------------------------
  16.  
  17. class Foo
  18. curry :say, :with => "good"
  19. curry :say_good, :with => "morning"
  20. curry :say_good, :with => "after noon"
  21. curry :say_good, :with => "night"
  22.  
  23. def say(*words)
  24. words.join(' ')
  25. end
  26. end
  27.  
  28. # using the (chained) curried methods in Foo
  29. Foo.new.say_good_after_noon("Bob") # => "good after noon Bob"
  30.  
  31. class Fixnum
  32. curry :*, :with => 2, :as => 'double'
  33. curry :/, :with => 2, :as => 'half'
  34. curry :-, :with => 1, :as => 'array_index'
  35. end
  36.  
  37. # using the curried methods in Fixnum
  38. 5.double # => 10
  39. 100.half # => 50
  40. %w(foo bar baz)[3.array_index] # => "baz"
  41.  
  42.  
  43. class Array
  44. curry :join, :with => ', ', :as => :csv
  45. curry :collect, :with => Proc.new {|x| x.name}, :as => :names
  46. end
  47.  
  48. class String
  49. curry :split, :with => /\s*,\s*/, :as => :parse_csv
  50. end
  51.  
  52. class Time
  53. curry :strftime, :with => "%Y-%m-%d %H:%M:%S", :as => "iso9075"
  54. end
  55.  
  56. # easy time formatting around your app
  57. Time.now.iso9075 # => "2008-04-17 14:11:31"
  58.  
  59. # curried methods on Array
  60. %w(foo bar baz).csv # => "foo, bar, baz"
  61.  
  62. # curried methods in String
  63. "foo, bar, baz".parse_csv # => ["foo", "bar", "baz"]
  64.  
  65. # and who hasn't done this: people.collect(&:name).join(', ')
  66. class Person
  67. attr_accessor :name
  68. def initialize(name)
  69. self.name = name
  70. end
  71. end
  72. people = [Person.new("Rob"), Person.new("Chris"), Person.new("Pat"), Person.new("Jim")]
  73.  
  74. # instead of doing the old collect and join directly, we use their curried friends
  75. people.names.csv # => "Rob, Chris, Pat, Jim"
Add Comment
Please, Sign In to add comment