Ruby for Instance / Sorting

# Define an array of strings
strings = ["apple", "banana", "cherry"]

# Sort the array alphabetically
sorted_strings = strings.sort
# => ["apple", "banana", "cherry"]

# Define an array of strings
strings = ["apple", "banana", "cherry"]

# Sort the array by the length of each string
sorted_strings = strings.sort_by { |string| string.length }
# => ["apple", "banana", "cherry"]

strings = ["apple", "banana", "cherry"]

# Sort the array in-place by the number of vowels in each string
strings.sort! do |a, b|
  # Count the number of vowels in each string
  a_vowels = a.count("aeiou")
  b_vowels = b.count("aeiou")

  # Compare the number of vowels in each string
  if a_vowels == b_vowels
    0
  elsif a_vowels < b_vowels
    -1
  else
    1
  end
end
# => ["cherry", "banana", "apple"]

Try on playground

Next: timers

made with by dfxe / source / license