Bird
0
0

What will be the output of this Ruby code?

medium📝 Predict Output Q4 of 15
Ruby - Enumerable and Collection Processing
What will be the output of this Ruby code?
fruits = ["kiwi", "apple", "banana"]
sorted = fruits.sort_by { |fruit| fruit.length }
puts sorted.join(", ")
Aapple, banana, kiwi
Bapple, kiwi, banana
Cbanana, apple, kiwi
Dkiwi, apple, banana
Step-by-Step Solution
Solution:
  1. Step 1: Determine lengths

    "kiwi" length = 4, "apple" = 5, "banana" = 6.
  2. Step 2: sort_by sorts ascending by length

    Sorted order is by increasing length: kiwi, apple, banana.
  3. Final Answer:

    kiwi, apple, banana -> Option D
  4. Quick Check:

    sort_by sorts ascending by default [OK]
Quick Trick: sort_by sorts ascending by default using block values [OK]
Common Mistakes:
  • Assuming alphabetical order instead of length
  • Confusing sort_by with sort
  • Expecting descending order without negation

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes