本文介绍了在 ruby​​ 中反转数组的顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下数组 [12,16,5,9,11,5,4] 它打印: 12,16,5,9,11,5,4.

I have the following array [12,16,5,9,11,5,4] it prints: 12,16,5,9,11,5,4.

我想让它打印:4,5,11,9,5,16,12

当我执行 array.reverse 时,它打印:

When I did array.reverse it printed:

4,5,11,9,5,61,21

它反转了单个数字 - 知道我怎么能阻止它吗?

It reversed individual numbers - any idea how I can stop that?

推荐答案

irb(main):001:0> a = [12,16,5,9,11,5,4]
=> [12, 16, 5, 9, 11, 5, 4]
irb(main):002:0> a.reverse
=> [4, 5, 11, 9, 5, 16, 12]

我没有看到你所看到的.

I'm not seeing what you're seeing.

编辑:扩展 Ben 注意到的内容,您可能正在反转字符串.

Edit: Expanding on what Ben noticed, you may be reversing a string.

irb(main):005:0> "12,16,5,9,11,5,4".reverse
=> "4,5,11,9,5,61,21"

如果您必须以这种方式反转字符串,您应该执行以下操作:

If you have to reverse a string in that manner, you should do something like the following:

irb(main):008:0> "12,16,5,9,11,5,4".split(",").reverse.join(",")
=> "4,5,11,9,5,16,12"

这篇关于在 ruby​​ 中反转数组的顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-14 22:02