在Ruby中从数组中创建二维数组

时间:2016-05-23 09:56:14

标签: arrays ruby

它可能是来自noob的问题,但是我无法做到......

我有阵列

arr = ["I", "wish", "I", "hadn't", "come"]

我需要做

[["I", "wish I hadn't come"], 
 ["I wish", "I hadn't come"],
 ["I wish I", "hadn't come"],
 ["I wish I hadn't", "come"]]

我理解如何分割该数组:

Array.new(n) { Array[arr.shift(n).join(" "), arr.join(" ")] }

但我认为n必须从1更改为(arr.size - 1)以填充所需数组的二维数组。 怎么做我不明白。

4 个答案:

答案 0 :(得分:2)

这应该适合你:

arr = ["I", "wish", "I", "hadn't", "come"]

new_arr = (0..arr.size-2).map {|i| [arr[0..i].join(" "), arr[i+1..-1].join(" ")] }

p new_arr

哪个输出:

[
  ["I", "wish I hadn't come"], 
  ["I wish", "I hadn't come"], 
  ["I wish I", "hadn't come"], 
  ["I wish I hadn't", "come"]
]

答案 1 :(得分:1)

Array#shift具有破坏性,它会改变你的数组:

arr = ["I", "wish", "I", "hadn't", "come"]

[arr.shift(2).join(" "), arr.join(" ")]
#=> ["I wish", "I hadn't come"]

arr
#=> ["I", "hadn't", "come"]

您可以改为使用Array#[]

arr = ["I", "wish", "I", "hadn't", "come"]

arr[0..2]
#=> ["I", "wish", "I"]

arr[3..-1]
#=> ["hadn't", "come"]

-1指的是最后一个元素。

答案 2 :(得分:0)

您可能需要考虑使用slice,它可以返回数组的选择部分,而不是shift,它可以为前n个元素实现相同的功能,但会修改原始数组这样做。将此与您从1到1的循环的想法相结合将帮助您实现目标。 for i in 1..n do语法是这样做的一种方式。

答案 3 :(得分:0)

以下是一种方法:

require "pp"

arr = ["I", "wish", "I", "hadn't", "come"]

r = (1...arr.size).collect  {|i| [arr.take(i).join(" "), arr.drop(i).join(" ")]}

pp r
#=> [["I", "wish I hadn't come"],
#   ["I wish", "I hadn't come"],
#   ["I wish I", "hadn't come"],
#   ["I wish I hadn't", "come"]]