Created
September 12, 2017 15:54
-
-
Save KevinSia/033f24d950cfbd7d3b5f3a80a348e61f to your computer and use it in GitHub Desktop.
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
# Your code here to sort the array | |
def dictionary_sort(array) | |
return if array.length <= 1 | |
array.sort { |word1, word2| word1.downcase <=> word2.downcase } | |
end | |
# writing `array.sort` is equivalent to writing `array.sort { |i, j| i <=> j }` | |
# .sort decides which item should be in the front by doing `<=> on each pair of items | |
# if the block gives -1, i goes to the front and j goes to the back | |
# if the block gives 1, j goes to the front and i goes to the back | |
# eg. ["z", "a", "f"].sort { |i, j| j <=> i } | |
# first the block will do "z" <=> "a" | |
# for the pair ["z", "a"] the block returns 1, thus it'll swap position of 'a' and 'z' | |
# the arr becomes ["a", "z", "f"] | |
# next the block will do "a" <=> "f" (second pair in the original array) | |
# for the pair ["a", "f"] the block returns -1, thus it'll not swap the position of 'a' and 'f' | |
# the arr becomes ["a", "z", "f"] | |
# finally the block does "z" <=> "f" | |
# for the pair ["z", "f"] the block returns 1, thus it'll swap 'f' and 'z' | |
# the arr finally becomes ["a", "f", "z"] | |
## NOTE: the pairs may come in differently when the array has length more than 3 | |
# if you want to observe the pairs you can do this | |
# def sort(arr) | |
# arr.sort do |i, j| | |
# puts "i = #{i}" | |
# puts "j = #{j}" | |
# puts | |
# i <=> j | |
# end | |
# end | |
def puts_with_prompt(str) | |
puts str | |
print ">> " | |
end | |
# ...your code here to initialize the program and take user input | |
def run | |
arr = [] | |
puts_with_prompt 'Type a word:' | |
until (str = gets.chomp) == '' | |
arr << str | |
puts_with_prompt "Type another word (or press enter to finish):" | |
end | |
result = dictionary_sort(arr) | |
puts "Congratulations! Your dictionary has #{arr.length} words:" | |
puts result | |
end | |
run |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment