Skip to content

Instantly share code, notes, and snippets.

@koriroys
Forked from ralphos/gist:3018324
Created June 29, 2012 19:45
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 koriroys/3020228 to your computer and use it in GitHub Desktop.
Save koriroys/3020228 to your computer and use it in GitHub Desktop.
UniqueArray Problem
source 'https://rubygems.org'
gem 'rspec', '2.11.0'
GEM
remote: https://rubygems.org/
specs:
diff-lcs (1.1.3)
rspec (2.11.0)
rspec-core (~> 2.11.0)
rspec-expectations (~> 2.11.0)
rspec-mocks (~> 2.11.0)
rspec-core (2.11.0)
rspec-expectations (2.11.1)
diff-lcs (~> 1.1.3)
rspec-mocks (2.11.1)
PLATFORMS
ruby
DEPENDENCIES
rspec (= 2.11)

For this problem you will be creating a Ruby class which behaves exactly like an array but will store only numbers, will store them in the order they were added and when adding new elements will ignore any duplicates. In this way it functions like a Ruby hash object in that each key has to be unique.

Examples

Creating an array from another array. Notice that only the first occurrence of the number 2 is kept:

UniqueArray.new([1,2,0,6,2,11]) 
#=> [1,2,0,6,11]

Creating an array by adding one element at a time:

m = UniqueArray.new()

[1,2,0,6,2,11].each do |new_element|
  m.add(new_element)
end

puts m
#=> [1,2,0,6,11]

Submit your ruby file containing the class you wrote. Also submit a test file which demonstrates how your class functions. You'll get bonus points if your test file uses the rSpec testing framework! ;)

require 'set'
class UniqueArray < Set
def initialize(input = [])
super(verified_input input)
end
def to_s
self.to_a.to_s
end
def add(element)
self << element if is_num? element
end
private
def is_num?(element)
element.kind_of? Numeric
end
def verified_input(input)
input.select {|e| e if is_num? e }
end
end
require './unique_array'
describe "UniqueArray" do
specify "when created with no arguments, it is empty" do
m = UniqueArray.new
expect(m).to be_empty
end
context "when created with an array that has" do
specify "no duplicates, it is equal to the input array" do
no_duplicates = [1, 2, 3, 4, 5]
m = UniqueArray.new no_duplicates
expect(m.to_a).to eq(no_duplicates)
end
specify "many duplicates, it only includes unique values" do
m = UniqueArray.new [1, 2, 3, 4, 5, 1, 5, 1]
expect(m.to_a).to eq([1, 2, 3, 4, 5])
end
specify "non-numeric values, it only includes numeric values" do
m = UniqueArray.new [4, "joe", "bob", 7]
expect(m.to_a).to eq([4, 7])
end
end
describe "#add" do
it "accepts numeric input" do
m = UniqueArray.new
m.add 4
expect(m.to_a).to eq([4])
end
it "rejects non-numeric input" do
m = UniqueArray.new
m.add('not a number')
expect(m).to be_empty
end
it "allows uniq numbers to be appended" do
m = UniqueArray.new [1,2,3]
m.add 4
expect(m.to_a).to eq([1, 2, 3, 4])
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment