【问题标题】:Why does this ruby sequence not work for double digit numbers?为什么这个红宝石序列不适用于两位数?
【发布时间】:2016-12-22 01:08:03
【问题描述】:

我正在用 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 = gets.to_i
  • 另外,使用a.sort,而不是a.sort!
  • 还有 JFYI:这个例子很简单,我们可以猜出你遇到了什么问题。但是将来,如果您声称“此代码不适用于这种情况”之类的内容,您必须详细说明:提供您期望的输出以及您实际获得的输出。此外,请确保代码包含所有必要的输入。简而言之,您需要一个minimal reproducible example。如果您不提供该信息,您的问题可能会引起反对票和近距离投票(也可能得不到任何答案)。
  • 好的,谢谢。我是新手,但下次我问问题时会听取您的建议!
  • 一些注意事项:您似乎确实在重复自己,所以考虑使用Integer#times;有两个get.chomps 毫无用处;你应该使用puts 而不是print

标签: ruby sorting


【解决方案1】:

对字符串数组或整数数组进行排序

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

【讨论】:

  • String#<=>String#succ 之间的差异总是让我感到困惑:'9'.succ > '9' #=> false
  • @Stefan '09'.succ > '09' ;)
  • 这不仅仅是数字:'z'.succ > 'z' #=> false ;-)
  • to_i 会为你做的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-30
  • 1970-01-01
  • 1970-01-01
  • 2015-09-28
  • 1970-01-01
相关资源
最近更新 更多