Skip to content

Instantly share code, notes, and snippets.

@ashmoran
Created October 31, 2011 22:34
Show Gist options
  • Save ashmoran/1329252 to your computer and use it in GitHub Desktop.
Save ashmoran/1329252 to your computer and use it in GitHub Desktop.
Proof of non-local returns in Ruby
# Some of the tests for this fail, in a way that's surprising to Python users...
# Why?
class List
def initialize(*elements)
@elements = elements
@elements.each do |e|
return if e.nil?
end
end
def handle_elements(&block)
block.(@elements, &block)
end
def find_3_and_recursively_add_1_on_the_way_back_up
handle_elements do |elements, &block|
return unless elements.first
if elements.first == 3
return elements.first
else
block.(elements.drop(1), &block) + 1
end
end
end
end
describe "blocks" do
context "no elements" do
let(:list) { List.new }
it "returns nil" do
list.find_3_and_recursively_add_1_on_the_way_back_up.should be_nil
end
end
context "1 element" do
context "no match" do
let(:list) { List.new(2) }
it "returns nil" do
list.find_3_and_recursively_add_1_on_the_way_back_up.should be_nil
end
end
context "that matches" do
let(:list) { List.new(3) }
it "returns one plus the element" do
list.find_3_and_recursively_add_1_on_the_way_back_up.should eq 3
end
end
end
context "2 elements" do
context "no match" do
let(:list) { List.new(2, 4) }
it "returns nil" do
list.find_3_and_recursively_add_1_on_the_way_back_up.should be_nil
end
end
context "match" do
let(:list) { List.new(2, 3) }
it "returns nil" do
list.find_3_and_recursively_add_1_on_the_way_back_up.should eq 4
end
end
end
context "3 elements" do
context "no match" do
let(:list) { List.new(2, 4, 5) }
it "returns nil" do
list.find_3_and_recursively_add_1_on_the_way_back_up.should be_nil
end
end
context "match" do
let(:list) { List.new(1, 2, 3) }
it "returns nil" do
list.find_3_and_recursively_add_1_on_the_way_back_up.should eq 5
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment