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)