Skip to content

Instantly share code, notes, and snippets.

@mclosson
Created January 30, 2014 19:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mclosson/8716691 to your computer and use it in GitHub Desktop.
Save mclosson/8716691 to your computer and use it in GitHub Desktop.
require 'minitest/autorun'
require 'set'
class FiniteSet < Set
def fetch(item)
if member?(item)
delete(item)
item
end
end
end
class FiniteSetTest < MiniTest::Unit::TestCase
def setup
@set = FiniteSet.new (1..10).to_a
end
def test_fetch_returns_item_requested_if_in_set
assert_equal 5, @set.fetch(5)
end
def test_fetch_returns_nil_if_item_not_in_set
assert_equal nil, @set.fetch(50)
end
def test_fetch_removes_item_requested_from_set
(1..10).to_a.each {|n| @set.fetch(n) if n.even?}
assert_equal FiniteSet.new([1, 3, 5, 7, 9]), @set
end
end
@caike
Copy link

caike commented Jan 30, 2014

Nice! Totally personal preference now, but for code like this, I also like to use guard clause:

class FiniteSet < Set
  def fetch(item)
    return unless member?(item)

    delete(item)
    item
  end
end

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