Skip to content

Instantly share code, notes, and snippets.

@dexterous
Last active January 13, 2024 09:20
Show Gist options
  • Save dexterous/a59b8b9c830e0d31fe15 to your computer and use it in GitHub Desktop.
Save dexterous/a59b8b9c830e0d31fe15 to your computer and use it in GitHub Desktop.
Ruby Procs, return & yield semantics
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
@dexterous
Copy link
Author

Compare with Paul Cantrell's snippet.

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