Skip to content

Instantly share code, notes, and snippets.

@kevinmarvin
Last active December 23, 2015 20:59
Show Gist options
  • Save kevinmarvin/a60d5055fa201f178324 to your computer and use it in GitHub Desktop.
Save kevinmarvin/a60d5055fa201f178324 to your computer and use it in GitHub Desktop.
Here is a version that adds your method to Array. Simplifies the overall usage and allows reuse wherever you like.
class Array
def wordlen_sort
replacement_array = []
unsorted_array = self.dup
while unsorted_array.count >= 2
temp = unsorted_array.shift
counter = unsorted_array.count
unsorted_array.cycle(counter) do |word|
if temp.length < word.length
temp = temp
elsif temp.length > word.length
unsorted_array << temp
temp = unsorted_array.shift
end
end
replacement_array << temp
end
if unsorted_array.count < 2
replacement_array << unsorted_array.first
end
self.clear
self << replacement_array
self.flatten
end
end
def create_array
puts "Type as many words as you want to create an array."
puts "Just press enter in a blank gets to exit"
one_array = []
while true
input = gets.chomp
one_array << input
if input == ''
one_array.pop
break
end
end
puts "Your unsorted array: #{one_array} "
return one_array
end
create_array
puts
puts "Your sorted array #{empty_array.wordlen_sort}" # the returned value shows up here.
@hayduke19us
Copy link

oh cool, thanks kevin. I'm just now learning about making my own class' so this is very helpful!

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