简体   繁体   English

在Ruby中以相反顺序打印多位元素的数组

[英]Printing array of multi-digit elements in reverse order in ruby

How to print an array of elements in reverse order not just single digit number but also multi-digit numbers. 如何以相反的顺序打印元素数组,不仅是单个数字,还包括多个数字。

[2, 5, 6 7]

It should print the array elements in reverse order as 7 6 5 2 by following a space for each number. 它应该按照每个数字的空格,以7 6 5 2的相反顺序打印数组元素。

I already wrote the code for this. 我已经为此编写了代码。

   puts "Enter the array elements"
    arr = gets.strip
    arr = arr.split(' ').map(&:to_i)
    x = arr.reverse_each {|f| }
    z = x.join(" ")
    print z.reverse

That is cool with single digit numbers, how can I reverse the multi-digit numbers in an array of inputs given by the user input like: 这对于单位数字很酷,如何在用户输入所给定的输入数组中反转多位数数字,例如:

[45, 76, 87 ] # this should reverse the array as `87 76 45`


[556, 674, 878 ] # this should reverse the array as `878 674 556`
[8797, 7347, 9374 ] # this should reverse the array as `9374 7374 8797`

If you like one-liners: 如果您喜欢单线:

gets.strip.split(' ').reverse.join(' ')

This will take the input 1 2 3 45 678 9 and convert it to "9 678 45 3 2 1" 这将采用输入1 2 3 45 678 9并将其转换为"9 678 45 3 2 1"

Input: [8797, 7347, 9374 ] 输入: [8797, 7347, 9374 ]

Output: "9374 7374 8797" 输出: "9374 7374 8797"

arr = gets.chomp
arr = arr.split(' ').map(&:to_i)
x = arr.reverse.join(' ')
print x

Use reverse and join chained and it should return a String type that joined your reversed array. 使用reversejoin连锁,它应该返回一个String即加入你的反数组类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM