Skip to content

Instantly share code, notes, and snippets.

@SolomonHD
Created February 24, 2015 16:35
Show Gist options
  • Save SolomonHD/744bbf3247250fe62033 to your computer and use it in GitHub Desktop.
Save SolomonHD/744bbf3247250fe62033 to your computer and use it in GitHub Desktop.
24FEB15
require 'minitest/autorun'
require 'minitest/pride'
# Write a method which accepts an array and returns a hash. Each item in the
# array will be a string, and the returned hash should have last names as keys
# and first names as values.
# WRITE YOUR CODE HERE. Name your method `names`.
def names(array)
hash = {}
return hash if array == nil
array.each |n| do
last_name = n.split.last
first_name = n.split.first
hash = {last_name => first_name}
hash[:last_name] = first_name
end
return hash
end
class ArrayAndHashChallenge < MiniTest::Test
def test_one_name
expected = {"Washington" => "George"}
assert_equal expected, names(["George Washington"])
end
def test_complex_name
expected = {"Adams" => "John"}
assert_equal expected, names(["John Quincy Adams"])
end
def test_two_names
expected = {"Washington" => "George", "Adams" => "John"}
assert_equal expected, names(["George Washington", "John Quincy Adams"])
end
def test_no_names
assert_equal Hash.new, names(Array.new)
end
def test_no_array
assert_equal Hash.new, names(nil)
end
def test_last_names_overwrite
expected = {"Washington" => "George", "Roosevelt" => "Franklin"}
assert_equal expected, names(["George Washington", "Theodore Roosevelt", "Franklin Roosevelt"])
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment