【发布时间】:2016-03-09 15:10:03
【问题描述】:
如何以相反的顺序打印一个元素数组,不仅是一位数字,还有多位数字。
[2, 5, 6 7]
它应该以相反的顺序将数组元素打印为7 6 5 2,每个数字后面都有一个空格。
我已经为此编写了代码。
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
单个数字很酷,我如何反转用户输入给出的输入数组中的多位数字,例如:
[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`
【问题讨论】:
-
什么是
n?上述代码中从未使用过。 -
n仅用于了解数组包含的许多元素。但是,我在上面的代码中没有使用n。也许我应该删除该代码。! -
我没有时间发布答案,但这里有一个提示:两个 Ruby 核心类有一个
reverse方法,Array和String。您使用的是后者。 -
puts gets.strip.split(' ').map(&:to_i).reverse.inspect -
感谢您的点击。我得到了相同的输出
[34, 54,76] => [67, 45, 43]' with bothreverse` 方法reverse_each和reverse这不是我想要的。