Why doesn't this ruby โ€‹โ€‹sequence work for double digits?

I created a program with ruby โ€‹โ€‹to organize sequences of numbers. It worked perfectly, except when it came to two-digit numbers, here is the code:

print "Hello participant today we will be rearranging your numbers from smallest to largest, press enter to continue!!"
gets.chomp

print "Please enter your first number"
n1 = gets.chomp

print "Please enter your second number"
n2 = gets.chomp

print "Please enter your third number"
n3 = gets.chomp

print "Please enter your fourth number"
n4 = gets.chomp

print "Please enter your fifth number"
n5 = gets.chomp

a = [n1, n2, n3, n4, n5]

print "your numbers from smallest to largest are: #{a.sort!}"
gets.chomp

print "thank you for participating, See you next time!!"
+4
source share
1 answer

Sort an array of strings or an array of integers

[n1, n2, n3, n4, n5]is an array of strings, and the strings are compared with the lexicographic order .

["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"].sort
#=> ["1", "10", "11", "12", "2", "3", "4", "5", "6", "7", "8", "9"]

["12", "11", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10"].sort_by(&:to_i)
#=> ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"]

So you need to:

print "your numbers from smallest to largest are: #{a.sort_by(&:to_i)}"

or just convert your string array to an integer array:

a = [n1, n2, n3, n4, n5].map(&:to_i)

print "your numbers from smallest to largest are: #{a.sort}"

Refactoring

Here's a shorter way to write a script:

puts "Hello participant today we will be rearranging your numbers from smallest to largest, press enter to continue!!"
gets

a = %w(first second third fourth fifth).map do |ordinal|
  puts "Please enter your #{ordinal} number"
  gets.to_i
end

puts "Your numbers from smallest to largest are: #{a.sort}"
gets

puts "Thank you for participating, See you next time!!"
+7
source

Source: https://habr.com/ru/post/1664414/


All Articles