Ruby Array Exercises: Sort a given array of strings by length
Ruby Array: Exercise-48 with Solution
Write a Ruby program to sort a given array of strings by length.
Write a Ruby program to iterate over the first n elements of a given array.
Ruby Code:
arra1 = ['abcde', 'abdf', 'adeab', 'abdgeee', 'bdefa', 'abc', 'ab', 'a', 'bacdef']
print "Original array:\n"
print arra1
print "\nSorted array of strings by length\n"
arra1 = arra1.sort_by(&:length)
print arra1
Output:
Original array: ["abcde", "abdf", "adeab", "abdgeee", "bdefa", "abc", "ab", "a", "bacdef"] Sorted array of strings by length ["a", "ab", "abc", "abdf", "abcde", "adeab", "bdefa", "bacdef", "abdgeee"]
Flowchart:
Ruby Code Editor:
Contribute your code and comments through Disqus.
Previous: Write a Ruby program to iterate over the first n elements of an given array.
Next: Ruby String Exercises
What is the difficulty level of this exercise?
- New Content published on w3resource:
- HTML-CSS Practical: Exercises, Practice, Solution
- Java Regular Expression: Exercises, Practice, Solution
- Scala Programming Exercises, Practice, Solution
- Python Itertools exercises
- Python Numpy exercises
- Python GeoPy Package exercises
- Python Pandas exercises
- Python nltk exercises
- Python BeautifulSoup exercises
- Form Template
- Composer - PHP Package Manager
- PHPUnit - PHP Testing
- Laravel - PHP Framework
- Angular - JavaScript Framework
- Vue - JavaScript Framework
- Jest - JavaScript Testing Framework