【问题标题】:How can I change the starting and ending items of an array while following the same order?如何在遵循相同顺序的同时更改数组的开始和结束项?
【发布时间】:2020-03-26 07:21:08
【问题描述】:

我想对数组进行排序

order = ['B', 'E', 'A', 'D', 'G', 'C', 'F']

以一种会返回的方式

['F', 'B', 'E', 'A', 'D', 'G', 'C']

换句话说,order 的最后一个元素应该移到开头,所有其他元素应该右移一个位置。

将返回一个新数组(order 不会被修改)。我该怎么做?

【问题讨论】:

  • 你想旋转阵列吗?
  • 是的,不知道 Ruby 有办法做到这一点。谢谢
  • 首先要做的是通过Array的实例方法,寻找一个可以完成这项工作的方法。如果你这样做了,你会找到rotate。 (如果失败,请查看Enumerable 模块。)。

标签: arrays ruby sorting


【解决方案1】:

假设您的返回值是后续输出,您可以使用rotate 方法:

order.rotate(-1)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-21
    • 1970-01-01
    • 2021-08-11
    • 1970-01-01
    • 1970-01-01
    • 2021-09-30
    相关资源
    最近更新 更多