Last active
August 29, 2015 13:56
-
-
Save zillou/9318837 to your computer and use it in GitHub Desktop.
Fake set implementation in Ruby
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
# filename: spec/fake_set_spec.rb | |
require 'spec_helper' | |
require 'fake_set' | |
describe FakeSet, '#union' do | |
it "unions elements of two set" do | |
set1 = FakeSet.new([1, 2, 3]) | |
set2 = FakeSet.new([3, 4, 5]) | |
expect(set1.union(set2).data).to eq [1, 2, 3, 4, 5] | |
end | |
end | |
# filename: lib/fake_set.rb | |
class FakeSet | |
def initialize(*elements) | |
@data = elements | |
end | |
def <<(new_element) | |
@data << new_element unless @data.index(new_element) | |
self | |
end | |
def each | |
if block_given? | |
@data.each {|e| yield e } | |
else | |
Enumerator.new(self, :each) | |
end | |
end | |
def data | |
@data.dup | |
end | |
def union(set) | |
set.each do |el| | |
self << el | |
end | |
self | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment