Last active
January 13, 2024 09:20
-
-
Save dexterous/a59b8b9c830e0d31fe15 to your computer and use it in GitHub Desktop.
Ruby Procs, return & yield semantics
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'rubygems' | |
require 'expectations' | |
Expectations do | |
expect(1){ proc { |a| a }.call(1) } | |
expect([1, 2]){ proc { |a| a }.call(1, 2) } #fails | |
expect(1){ proc { |a, b| a }.call(1, 2) } | |
expect(1){ Proc.new { |a| a }.call(1) } | |
expect([1, 2]){ Proc.new { |a| a }.call(1, 2) } #fails | |
expect(1){ Proc.new { |a, b| a }.call(1, 2) } | |
def foo | |
x = proc { return :block } | |
x.call() | |
return :method | |
end | |
expect foo().to.be == :method #fails | |
def bar | |
x = Proc.new { return :block } | |
x.call() | |
return :method | |
end | |
expect bar().to.be == :block | |
=begin | |
def boo | |
yield :block | |
return :method | |
end | |
# does not compile as return not allowed in implicit block | |
expect boo{ |a| return a }.to.be == :method | |
def baz &block | |
block.call(:block) | |
return :method | |
end | |
# not even when block param is explicitly declared in method | |
expect baz{ |a| return a }.to.be == :block | |
=end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Compare with Paul Cantrell's snippet.