Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Sorting in Ruby

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 164
    Comment on it

    Using sort method we can sort any string, numbers, even classes either in ascending order or descending order .To sort an array ,you need to compare its element using <, >, <=, >= .

    return -1 if x < y
    return 0 if x = y
    return 1 if x > y
    
    Example :

    puts "enter names "
    names = [ ] 
    while true
    nam = gets.chomp
    if nam == ' '
    break
    else 
    names.push (nam)
    end
    puts names.sort or names.sort { | x, y | x <=> y } // both are same
    puts after sorting
    

    Output :

    enter names
    mukesh
    ashish
    ravi
    
    after sorting
    
    ashish
    mukesh
    ravi
    

 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: