Complete the code to sort the array of numbers in ascending order using sort_by.
numbers = [5, 2, 9, 1] sorted = numbers.sort_by { |n| [1] } puts sorted
The block variable n represents each element. Using n as the key sorts by the number itself.
Complete the code to sort the array of words by their length using sort_by.
words = ["apple", "pear", "banana", "fig"] sorted = words.sort_by { |word| [1] } puts sorted
Sorting by word.length sorts words by their length.
Fix the error in the code to sort people by age using sort_by.
people = [{name: "Anna", age: 30}, {name: "Bob", age: 25}]
sorted = people.sort_by { |person| [1] }
puts sorted.map { |p| p[:name] }Hashes use symbols as keys accessed with person[:age]. Using person.age causes an error.
Fill both blanks to sort an array of strings by their last character using sort_by.
words = ["cat", "dog", "bird"] sorted = words.sort_by { |word| word[1][2] } puts sorted
Using word[-1] gets the last character. Applying .downcase ensures case-insensitive sorting.
Fill all three blanks to sort an array of hashes by the length of the name in descending order using sort_by.
people = [{name: "Anna"}, {name: "Elizabeth"}, {name: "Bob"}]
sorted = people.sort_by { |person| [1] [2] [3]1 }
puts sorted.map { |p| p[:name] }To sort descending by name length, return negative lengths using - person[:name].length *1. Since sort_by sorts ascending on the returned values, more negative values (longer names) appear first.