Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- [a] -> [a] -> (a -> a -> a) -> [a]
- combine([1,2,3], [2,3,4], plus_func) => [3,5,7]
- combine([1,2,3], [2,3,4], multiply_func) => [2,6,12]
- def combine a, b
- a.zip(b).map { |i| yield i[0], i[1] }
- end
- puts combine([1,2,3], [2,3,4]) { |i, j| i+j }
- def combine(a, b, &block)
- a.zip(b).map(&block)
- end
- def combine(a, b, *args, &block)
- a.zip(b, *args).map(&block)
- end
- def combine(a1, a2)
- i = 0
- result = []
- while a1[i] && a2[i]
- result << yield(a1[i], a2[i])
- i+=1
- end
- result
- end
- sum = combine([1,2,3], [2,3,4]) {|x,y| x+y}
- prod = combine([1,2,3], [2,3,4]) {|x,y| x*y}
- p sum, prod
- =>
- [3, 5, 7]
- [2, 6, 12]
- def combine(*args)
- i = 0
- result = []
- while args.all?{|a| a[i]}
- result << yield(*(args.map{|a| a[i]}))
- i+=1
- end
- result
- end
- def combine(*args)
- args.first.zip(*args[1..-1]).map {|a| yield a}
- end
- sum = combine([1,2,3], [2,3,4], [3,4,5]) {|ary| ary.inject{|t,v| t+=v}}
- prod = combine([1,2,3], [2,3,4], [3,4,5]) {|ary| ary.inject(1){|t,v| t*=v}}
- p sum, prod
- class Symbol
- # Turns the symbol into a simple proc, which is especially useful for enumerations.
- def to_proc
- Proc.new { |*args| args.shift.__send__(self, *args) }
- end
- end
- (1..100).inject(&:+)
Add Comment
Please, Sign In to add comment