In ruby if you want to sort an array of strings based on the length of its element, you can use the code given below. i.e If you want the word having the least number of characters in it to come first and arrange other words in this manner as well, you can use the given code.
words = ["India","Food","Culture","Hostel","Railways"]
=> ["India", "Food", "Culture", "Hostel", "Railways"]
2.1.5 :025 > res = words.sort {|l, r| l.length <=> r.length}
=> ["Food", "India", "Hostel", "Culture", "Railways"]
Thus we can see that the word having the least character count comes at the beginning and the word having the maximum character count appears at last.
If we wish to sort it in reverse order, then we can write
res = words.sort {|l, r| r.length <=> l.length}
=> ["Railways", "Culture", "Hostel", "India", "Food"]
0 Comment(s)