Skip to content

Instantly share code, notes, and snippets.

@ScottGo
Created April 4, 2013 20:38
Show Gist options
  • Save ScottGo/5314148 to your computer and use it in GitHub Desktop.
Save ScottGo/5314148 to your computer and use it in GitHub Desktop.
# shortest_string is a method that takes an array of strings as its input
# and returns the shortest string
# +array+ is an array of strings
# shortest_string(array) should return the shortest string in +array+
# If +array+ is empty the method should return nil
# array.sort.first
def shortest_string(array)
new_count = [ ]
array.each do |count|
new_count.push(count.length)
end
new_count.sort.first
end
# array = ['cat', 'zzzzzzz', 'apples']
@ScottGo
Copy link
Author

ScottGo commented Apr 4, 2013

THIS IS THE TEST:

describe 'shortest_string' do
it "returns nil when the array is empty ([])" do
shortest_string([]).should be_nil
end

it "returns '' when that is the only element in the array" do
shortest_string(['']).should eq ''
end

it "returns 'cat' when that is the only element in the array" do
shortest_string(['cat']).should eq 'cat'
end

it "returns the 'zzzzzzz' with the example array" do
shortest_string(['cat', 'zzzzzzz', 'apples']).should eq 'cat'
end

it "returns the shortest string regardless of ordering" do
# This creates an array containing ['a', 'aa', ...]
# up to 10 characters long, but randomly ordered
array = Array.new(10) { |i| 'a' * (i + 1) }.shuffle

shortest_string(array).should eq 'a'

end
end

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