如何将数组中的每个元素转换为自己的数组?

时间:2017-02-13 18:29:06

标签: arrays ruby

使用Ruby 2.4。我有一系列字符串......

["a", "b", "c"]

如何进行上述操作并将每个元素转换为自己的一个元素数组?所以我希望这样一个操作的结果是

[["a"], ["b"], ["c"]]

3 个答案:

答案 0 :(得分:3)

您可以使用zip

["a", "b", "c"].zip #=> [["a"], ["b"], ["c"]] 

答案 1 :(得分:2)

a.map { |s| Array(s) }

a.map { |s| [s] }

答案 2 :(得分:2)

此外,您可以使用combinationpermutation方法,它还提供更多功能

a.combination(1).to_a
#=> [['a'], ['b'], ['c']]
a.combination(2).to_a
#=> [["a", "b"], ["a", "c"], ["b", "c"]]     

a.permutation(1).to_a
#=> [['a'], ['b'], ['c']]
a.permutation(2).to_a
#=> [["a", "b"], ["a", "c"], ["b", "a"], ["b", "c"], ["c", "a"], ["c", "b"]]
相关问题