0
0
Rubyprogramming~5 mins

Sort_by for custom sorting in Ruby - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
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 sorted
It 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?
AA new sorted array
BThe original array sorted in place
CA boolean indicating if sorting succeeded
DThe number of elements sorted
Which block would sort an array of numbers by their absolute value?
Aarray.sort_by { |n| n.abs }
Barray.sort_by { |n| -n }
Carray.sort_by { |n| n }
Darray.sort_by { |n| n.to_s }
What is a benefit of using sort_by instead of sort with a block?
AIt modifies the original array
BIt is slower but more readable
CIt calculates sort keys once for efficiency
DIt only works with numbers
How would you sort an array of hashes by the value of the key :score?
Aarray.sort_by { |h| h.score }
Barray.sort_by(:score)
Carray.sort { |a, b| a[:score] <=> b[:score] }
Darray.sort_by { |h| h[:score] }
What will ["cat", "dog", "bird"].sort_by { |w| w.length } return?
A["cat", "bird", "dog"]
B["cat", "dog", "bird"]
C["dog", "cat", "bird"]
D["bird", "cat", "dog"]
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.