Skip to content

Instantly share code, notes, and snippets.

@stevegraham
Created September 20, 2012 00:01
Show Gist options
  • Select an option

  • Save stevegraham/3753125 to your computer and use it in GitHub Desktop.

Select an option

Save stevegraham/3753125 to your computer and use it in GitHub Desktop.
def gen_times(factor)
return Proc.new { |n| n * factor }
end
times3 = gen_times(3)
times5 = gen_times(5)
times3.call(12) #=> 36
times5.call(5) #=> 25
times3.call(times5.call(4)) #=> 60
@proc = Proc.new { |a,b,c| puts [a,b,c].inspect }
@lambda = lambda { |a,b,c| puts [a,b,c].inspect }
@proc.call 1,2,3
# => [1,2,3]
@lambda.call 1,2,3
# => [1,2,3]
# Proc is chilled out. Proc just ignores any more arguments than it is expecting
@proc.call 1,2,3,4,5,6,7,8
# => [1,2,3]
# Procs also pass in nil in lieu of missing arguments
@proc.call 1,2
# => [1, 2, nil]
# lambda is not so chill
@lambda.call 1,2,3,4,5,6,7,8
# => ArgumentError: wrong number of arguments (8 for 3)
@lambda.call 1,2
# => ArgumentError: wrong number of arguments (2 for 3)
module Kernel
def proc(&block)
Proc.new &block
end
end
def proc_object
obj = Proc.new { return 'returning from the proc' }
obj[]
return 'returning from the method body'
end
def lambda_object
obj = lambda { return 'returning from the proc' }
obj[]
return 'returning from the method body'
end
proc_object
#=> "returning from the proc"
lambda_object
#=> "returning from the method body"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment