Skip to content

Instantly share code, notes, and snippets.

@jimweirich
Created August 25, 2010 22:38
Show Gist options
  • Save jimweirich/550441 to your computer and use it in GitHub Desktop.
Save jimweirich/550441 to your computer and use it in GitHub Desktop.
# What's the output of this program?
# Compare Ruby 1.8 to 1.9.
def fl; lambda { return 1 }.call; 2; end
def fp; proc { return 1 }.call; 2; end
def fPn; Proc.new { return 1 }.call; 2; end
puts fl
puts fp
puts fPn
# Advanced considersions
def make_lambda(&block) lambda(&block) end
def make_proc(&block) block end
def fml; make_lambda { return 1 }.call; 2; end
def fmp; make_proc { return 1 }.call; 2; end
puts fml
puts fmp
# Ruby 1.9 addition to the return scope issue.
def fsp; ->() { return 1; }.call; 2; end
puts fsp
@baroquebobcat
Copy link

That's fun. So 'proc' acts like 'lambda' in 1.8 and like 'Proc.new' in 1.9.

see also:

$ irb
>>  lambda {|a,b,c| p [a,b,c]}.call
ArgumentError: wrong number of arguments (0 for 3)
    from (irb):1
    from (irb):1:in `call'
    from (irb):1
>> proc {|a,b,c| p [a,b,c]}.call
ArgumentError: wrong number of arguments (0 for 3)
    from (irb):2
    from (irb):2:in `call'
    from (irb):2
>> Proc.new {|a,b,c| p [a,b,c]}.call
[nil, nil, nil]
=> nil


$ irb-ruby-1.9.2-p0
ruby-1.9.2-p0 > lambda {|a,b,c| p [a,b,c]}.call
ArgumentError: wrong number of arguments (0 for 3)
    from (irb):1:in `block in irb_binding'
    from (irb):1:in `call'
    from (irb):1
    from /Users/nick/.rvm/rubies/ruby-1.9.2-p0/bin/irb:17:in `<main>'
ruby-1.9.2-p0 > proc {|a,b,c| p [a,b,c]}.call
[nil, nil, nil]
=> [nil, nil, nil] 
ruby-1.9.2-p0 > Proc.new {|a,b,c| p [a,b,c]}.call
[nil, nil, nil]
 => [nil, nil, nil] 

@jimweirich
Copy link
Author

Summary ... Here's the take away from this exercise:

Behaviors:

Function Behavior:

  • Must be called with correct number of parameters
  • Returns will return from the anonymous function

Block Behavior:

  • Assignment semantics for parameter passing (i.e. number of parameters not checked)
  • Returns will return from method in the surrounding scope.

Classification

Things with Function Behavior

  • lambda
  • proc (in Ruby 1.8)
  • -> (stabby procs in Ruby 1.9)

Things with Block Behavior

  • Proc.new
  • proc (in Ruby 1.9)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment