在保留序列的同时获取数组项的所有组合 - Ruby

Oll*_*ass 2 ruby arrays combinations sequence

给定一个字符串数组

["the" "cat" "sat" "on" "the" "mat"]
Run Code Online (Sandbox Code Playgroud)

我希望从任何起始位置按顺序获得所有项目组合,例如

["the"]
["the" "cat"]
["the" "cat" "sat"]
...
["cat" "sat" "on" "the" "mat"]
["sat" "on" "the" "mat"]
["on" "the" "mat"]
...
["sat" "on"]
["sat" "on" "the"]
Run Code Online (Sandbox Code Playgroud)

不允许例如原始序列中的组合或缺少元素的组合

["sat" "mat"] # missing "on"
["the" "on"]  # reverse order
Run Code Online (Sandbox Code Playgroud)

我还想知道这个操作是否有一个特定的名称,或者是否有更简洁的描述方式.

谢谢.

Mla*_*vić 6

如果你是单行,你可能会尝试

(0..arr.length).to_a.combination(2).map{|i,j| arr[i...j]}
Run Code Online (Sandbox Code Playgroud)

顺便说一句,我认为这些被称为数组的"所有后续序列".