0
0
Rubyprogramming~10 mins

Sort_by for custom sorting in Ruby - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to sort the array of numbers in ascending order using sort_by.

Ruby
numbers = [5, 2, 9, 1]
sorted = numbers.sort_by { |n| [1] }
puts sorted
Drag options to blanks, or click blank then click option'
Anumbers
Bn
Csorted
Dn.to_s
Attempts:
3 left
💡 Hint
Common Mistakes
Using the whole array instead of the element inside the block.
Using a variable not defined in the block.
2fill in blank
medium

Complete the code to sort the array of words by their length using sort_by.

Ruby
words = ["apple", "pear", "banana", "fig"]
sorted = words.sort_by { |word| [1] }
puts sorted
Drag options to blanks, or click blank then click option'
Awords.length
Bword
Cword.length
Dword[0]
Attempts:
3 left
💡 Hint
Common Mistakes
Sorting by the whole word instead of its length.
Using the array's length instead of the word's length.
3fill in blank
hard

Fix the error in the code to sort people by age using sort_by.

Ruby
people = [{name: "Anna", age: 30}, {name: "Bob", age: 25}]
sorted = people.sort_by { |person| [1] }
puts sorted.map { |p| p[:name] }
Drag options to blanks, or click blank then click option'
Aperson[:age]
Bperson.age
Cperson[age]
Dperson['age']
Attempts:
3 left
💡 Hint
Common Mistakes
Using dot notation to access hash keys.
Using string keys instead of symbol keys.
4fill in blank
hard

Fill both blanks to sort an array of strings by their last character using sort_by.

Ruby
words = ["cat", "dog", "bird"]
sorted = words.sort_by { |word| word[1][2] }
puts sorted
Drag options to blanks, or click blank then click option'
A[-1]
B[0]
C.downcase
D.upcase
Attempts:
3 left
💡 Hint
Common Mistakes
Using [0] to get the first character instead of last.
Not normalizing case, causing unexpected order.
5fill in blank
hard

Fill all three blanks to sort an array of hashes by the length of the name in descending order using sort_by.

Ruby
people = [{name: "Anna"}, {name: "Elizabeth"}, {name: "Bob"}]
sorted = people.sort_by { |person| [1] [2] [3]1 }
puts sorted.map { |p| p[:name] }
Drag options to blanks, or click blank then click option'
Aperson[:name].length
B-
C*
D+
Attempts:
3 left
💡 Hint
Common Mistakes
Sorting ascending instead of descending.
Using dot notation for hash keys.
Missing the negative sign to reverse order.