Skip to content

Instantly share code, notes, and snippets.

@KBeltz
Last active August 29, 2015 14:22
Show Gist options
  • Save KBeltz/9518deb73ed8aa5c7ee6 to your computer and use it in GitHub Desktop.
Save KBeltz/9518deb73ed8aa5c7ee6 to your computer and use it in GitHub Desktop.
Word Connector
require_relative "word_connector.rb"
# gets user input in the form of a string
puts "Please list your favorite color or colors, without using commas:"
favorite_colors = gets.chomp
# allows only valid input
while favorite_colors.include?(",")
puts "Invalid. Please try again without using commas:"
favorite_colors = gets.chomp
end
# splits string at each " " into an array
favorite_colors = favorite_colors.split
# creates a new instance of the WordConnector class
colors = WordConnector.new(favorite_colors)
# calls join_color_array method and provides output
puts colors.join_color_array(favorite_colors)
# creates WordConnector class with one attribute
class WordConnector
attr_accessor :color_array
# initializes WordConnector class
#
# color_array - array with string values representing colors
#
# returns self
def initialize(color_array)
@color_array = color_array
end
# join_color_array method joins the array into a string based on the length
#
# array - array
#
# returns a string
def join_color_array(array)
if array.length == 1
array.join
elsif array.length == 2
array.insert(-2, "and")
array.join(" ")
else
"#{array[0..-2].join(", ")}, and #{array[-1]}"
end
end
end
require "minitest/autorun"
require_relative "word_connector.rb"
class WordConnectorTest < Minitest::Test
# One of my specs is that the join_color_array method should join the array
# properly based on the length of the array
def test_join_color_array
array1 = ["eggplant"]
array2 = ["cerulean", "crimson"]
array3 = ["violet", "sunshine", "burgundy"]
array4 = ["hot hot pink", "atomic turquoise", "purple haze", "ultraviolet"]
colors1 = WordConnector.new(array1)
colors2 = WordConnector.new(array2)
colors3 = WordConnector.new(array3)
colors4 = WordConnector.new(array4)
assert_equal("eggplant", colors1.join_color_array(array1))
assert_equal("cerulean and crimson", colors2.join_color_array(array2))
assert_equal("violet, sunshine, and burgundy", colors3.join_color_array(array3))
assert_equal("hot hot pink, atomic turquoise, purple haze, and ultraviolet", colors4.join_color_array(array4))
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment