Recall & Review
beginner
What does the
sort_by method do in Ruby?It sorts elements of a collection based on the value returned by the block you provide. It creates a new sorted array without changing the original.
Click to reveal answer
beginner
How do you use
sort_by to sort an array of strings by their length?You pass a block that returns the length of each string: <br>
array.sort_by { |str| str.length }Click to reveal answer
intermediate
Why might you choose
sort_by over sort for custom sorting?sort_by is often faster and simpler when sorting by a computed value because it calculates the sort keys once, then sorts by those keys.Click to reveal answer
beginner
What will this code output?<br>
words = ["apple", "pear", "banana"]
sorted = words.sort_by { |w| w[-1] }
puts sortedIt sorts words by their last letter:<br>["banana", "apple", "pear"] because 'a' < 'e' < 'r'.
Click to reveal answer
intermediate
Can
sort_by be used to sort by multiple criteria? How?Yes. Return an array of values in the block, like:<br>
array.sort_by { |x| [x.age, x.name] } to sort by age, then name.Click to reveal answer
What does
sort_by return in Ruby?✗ Incorrect
sort_by returns a new array sorted by the block's values, leaving the original unchanged.Which block would sort an array of numbers by their absolute value?
✗ Incorrect
Using
n.abs sorts numbers by their absolute value.What is a benefit of using
sort_by instead of sort with a block?✗ Incorrect
sort_by calculates the sorting keys once, making it more efficient for complex sorting.How would you sort an array of hashes by the value of the key :score?
✗ Incorrect
You access the :score key inside the block to sort by it.
What will
["cat", "dog", "bird"].sort_by { |w| w.length } return?✗ Incorrect
It sorts words by length: cat (3), dog (3), bird (4). Since cat and dog have the same length, the stable sort preserves their original relative order.
Explain how
sort_by works in Ruby and give an example of sorting strings by their last character.Think about how you tell Ruby what to sort by using a block.
You got /4 concepts.
Describe how to sort an array of objects by multiple attributes using
sort_by.Use an array inside the block to specify multiple sort keys.
You got /3 concepts.