Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Sort an array of strings based on length of its elements in Ruby

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 831
    Comment on it


    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)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: