加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

为什么这个ruby序列不能用于双位数字?

发布时间:2020-12-17 02:49:38 所属栏目:百科 来源:网络整理
导读:我正在用 ruby创建一个程序来组织数字序列.除了涉及两位数字之外,它完美地工作,这里是代码: print "Hello participant today we will be rearranging your numbers from smallest to largest,press enter to continue!!"gets.chompprint "Please enter your
我正在用 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,n5]是一个字符串数组,字符串与lexicographic order进行比较.

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

["12","1","10"].sort_by(&:to_i)
#=> ["1","12"]

所以你需要:

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

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

a = [n1,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!!"

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读