class Array def iterate!(code) self.each_with_index do |n, i| self[i] = code.call(n) end end end array_1 = [1, 2, 3, 4] array_2 = [2, 3, 4, 5] square = lambda { |n| n ** 2} array_1.iterate!(square) array_2.iterate!(square) puts array_1.inspect puts array_2.inspect # => [1, 4, 9, 16] # => [4, 9, 16, 25]
This is eactly the same code as creating a proc [dzone.com] except the statement Proc.new has been changed to lambda. Lambda is slightly more advanced than Proc, as lambda handles specific code scenarios in a more controlled manner specifically validating the number of arguments supplied and allowing code to continue past an initial nested return statement. e.g.
# example-12.rb def generic_return(code) one, two = 1, 2 three, four = code.call(one, two) return "Give me a #{three} and a #{four}" end puts generic_return(lambda { |x, y| return x + 2, y + 2 }) puts generic_return(Proc.new { |x, y| return x + 2, y + 2 }) puts generic_return(Proc.new { |x, y| x + 2; y + 2 }) puts generic_return(Proc.new { |x, y| [x + 2, y + 2] }) # => Give me a 3 and a 4 # => *.rb:11: unexpected return (LocalJumpError) # => Give me a 4 and a # => Give me a 3 and a 4
Finally just to recap a Proc is a type of block however a Proc can be implemented independently from the context in which it is finally used e.g.
square = Proc.new {|n| n** 2}
- - - - - - - - - - - - - - - - - - - - - - - -
Eglence icin Chat, Sohbet deneyin.