为什么此红宝石序列不适用于两位数数字? [英] Why does this ruby sequence not work for double digit numbers?

查看:119
本文介绍了为什么此红宝石序列不适用于两位数数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用ruby创建一个程序来组织数字序列.除非涉及到两位数字,否则它的运行效果非常好,代码如下:

I was creating a program with ruby to organises sequences of numbers. It worked perfectly except when two digit numbers were involved, 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!!"

推荐答案

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

[n1, n2, n3, n4, n5]是一个字符串数组,并将字符串与词典顺序进行比较.

Sort array of strings or array of integers

[n1, n2, n3, n4, n5] is an array of strings, and strings are compared with 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)}"

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

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

这篇关于为什么此红宝石序列不适用于两位数数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆