How do I convert every element in an array to its

2020-04-19 05:48发布

问题:

Using Ruby 2.4. I have an array of strings ...

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

How do I take the above and convert each element into its own array of one element? So I would want the result of such an operation to be

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

?

回答1:

You can use zip:

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


回答2:

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

or

a.map { |s| [s] }


回答3:

Also, you can use combination or permutation methods, it also provide little bit more functionality

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"]]


标签: arrays ruby