gpt4 book ai didi

ruby - 为什么这个 ruby 序列不适用于两位数?

转载 作者:数据小太阳 更新时间:2023-10-29 07:26:39 24 4
gpt4 key购买 nike

我正在用 ruby​​ 创建一个程序来组织数字序列。它工作完美,除非涉及两位数,这里是代码:

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!!"

最佳答案

排序字符串数组或整数数组

[n1, n2, n3, n4, n5]是一个字符串数组,字符串与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"]

所以你需要:

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

或者只是将您的字符串数组转换为整数数组:

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

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

重构

这是编写脚本的一种较短的方法:

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!!"

关于ruby - 为什么这个 ruby 序列不适用于两位数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41261034/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com