Guest User

passing functions as arguments in ruby

a guest
Feb 27th, 2012
48
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.21 KB | None | 0 0
  1. [a] -> [a] -> (a -> a -> a) -> [a]
  2.  
  3. combine([1,2,3], [2,3,4], plus_func) => [3,5,7]
  4. combine([1,2,3], [2,3,4], multiply_func) => [2,6,12]
  5.  
  6. def combine a, b
  7. a.zip(b).map { |i| yield i[0], i[1] }
  8. end
  9.  
  10. puts combine([1,2,3], [2,3,4]) { |i, j| i+j }
  11.  
  12. def combine(a, b, &block)
  13. a.zip(b).map(&block)
  14. end
  15.  
  16. def combine(a, b, *args, &block)
  17. a.zip(b, *args).map(&block)
  18. end
  19.  
  20. def combine(a1, a2)
  21. i = 0
  22. result = []
  23. while a1[i] && a2[i]
  24. result << yield(a1[i], a2[i])
  25. i+=1
  26. end
  27. result
  28. end
  29.  
  30. sum = combine([1,2,3], [2,3,4]) {|x,y| x+y}
  31. prod = combine([1,2,3], [2,3,4]) {|x,y| x*y}
  32.  
  33. p sum, prod
  34.  
  35. =>
  36. [3, 5, 7]
  37. [2, 6, 12]
  38.  
  39. def combine(*args)
  40. i = 0
  41. result = []
  42. while args.all?{|a| a[i]}
  43. result << yield(*(args.map{|a| a[i]}))
  44. i+=1
  45. end
  46. result
  47. end
  48.  
  49. def combine(*args)
  50. args.first.zip(*args[1..-1]).map {|a| yield a}
  51. end
  52.  
  53. sum = combine([1,2,3], [2,3,4], [3,4,5]) {|ary| ary.inject{|t,v| t+=v}}
  54. prod = combine([1,2,3], [2,3,4], [3,4,5]) {|ary| ary.inject(1){|t,v| t*=v}}
  55. p sum, prod
  56.  
  57. class Symbol
  58. # Turns the symbol into a simple proc, which is especially useful for enumerations.
  59. def to_proc
  60. Proc.new { |*args| args.shift.__send__(self, *args) }
  61. end
  62. end
  63.  
  64. (1..100).inject(&:+)
Add Comment
Please, Sign In to add comment