Ruby:Ordering Your Library:Methodical Sorting:4/6Sorting With Control Flow
Sorting With Control Flow
Great! Now we need to add the right logic to our method.
If our method sees that rev is true, it should go ahead and reverse the sort. That is, it should use the combined comparison operator (also called the spaceship operator because... well, it looks like a spaceship) to order the array it receives in descending order. Remember, we can do that like this:
array.sort! { |item1, item2| item2 <=> item1}
In the context of alphabetizing, this says: "Hey Ruby! Sort the array in-place. Whenever you see two items, compare them and put the one further along in the alphabet first."
Instructions
Add an if/else statement inside your method. If rev is true, it should sort the array reverse-alphabetically; if rev is false (which happens if the user passes false or doesn't pass an argument for rev at all), it should sort the array in alphabetical order.
Outside your method, puts the sorted array. (This is so you can see all the fine work your method did.)
Call your method on an array of your choice to see it in action!
def alphabetize(arr, rev=false)
if rev
arr.sort { |item1, item2| item2 <=> item1 }
else
arr.sort { |item1, item2| item1 <=> item2 }
end
end
puts "A-Z: #{alphabetize(books)}"
puts "Z-A: #{alphabetize(books, true)}"
Great! Now we need to add the right logic to our method.
If our method sees that rev is true, it should go ahead and reverse the sort. That is, it should use the combined comparison operator (also called the spaceship operator because... well, it looks like a spaceship) to order the array it receives in descending order. Remember, we can do that like this:
array.sort! { |item1, item2| item2 <=> item1}
In the context of alphabetizing, this says: "Hey Ruby! Sort the array in-place. Whenever you see two items, compare them and put the one further along in the alphabet first."
Instructions
Add an if/else statement inside your method. If rev is true, it should sort the array reverse-alphabetically; if rev is false (which happens if the user passes false or doesn't pass an argument for rev at all), it should sort the array in alphabetical order.
Outside your method, puts the sorted array. (This is so you can see all the fine work your method did.)
Call your method on an array of your choice to see it in action!
def alphabetize(arr, rev=false)
if rev
arr.sort { |item1, item2| item2 <=> item1 }
else
arr.sort { |item1, item2| item1 <=> item2 }
end
end
puts "A-Z: #{alphabetize(books)}"
puts "Z-A: #{alphabetize(books, true)}"