How to Sort a String Characters Alphabetically in Ruby?
This article focuses on discussing how to sort a string’s characters alphabetically in Ruby.
Using Chars and Sort
Syntax:
sorted_string = string.chars.sort.join
Example:
In this example, the string is converted into an array of characters, and the sort method is used to sort the array.
# Original string
string = "w3wiki"
# Sort a string's characters alphabetically
# using chars and sort
sorted_string = string.chars.sort.join
puts sorted_string
Output
eeeefggkkorss
Using Split and Sort
Syntax:
sorted_string = string.split(”).sort.join
Example:
In this example the string is split into an array of characters and the sort method is used to sort the array.
# Original string
original_string = "w3wiki"
# Sort the string alphabetically
# Using String's each_char Method
# and Array's sort Method
sorted_string = ''
original_string.each_char { |char| sorted_string << char }
sorted_string = sorted_string.chars.sort.join('')
puts sorted_string
Output
eeeefggkkorss
Using Custom Sorting Algorithm
This method implements a custom sorting algorithm to sort the characters of the string str
.
Example:
In this example, the input string “geekforBeginner” is iterated multiple times until the string is sorted.
# Define a method to sort a string's characters
# alphabetically using a custom sorting algorithm.
def sort_string(str)
# Get the length of the input string.
str_length = str.length
# Initialize a variable to track whether
# the string is sorted.
sorted = false
# Continue iterating until the string is sorted.
until sorted
# Assume the string is sorted initially.
sorted = true
# Iterate through the characters of the string.
(str_length - 1).times do |i|
# Compare adjacent characters.
if str[i] > str[i + 1]
# If the current character is greater than
# the next one, swap them.
str[i], str[i + 1] = str[i + 1], str[i]
# Since a swap was made, the string is not yet sorted.
sorted = false
end
end
end
# Return the sorted string.
str
end
# Example string to be sorted.
example_string = "geekforBeginner"
# Call the method to sort the example string
# and print the result.
puts sort_string(example_string)
Output
eeeefggkkors