2

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
  • 1
    ["a", "b", "c"].each_cons(1).to_av#=> [["a"], ["b"], ["c"]] is yet another way. Commented Feb 13, 2017 at 20:54

4 Answers 4

6

You can use zip:

["a", "b", "c"].zip #=> [["a"], ["b"], ["c"]] 
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, I was previously iterating over each id passing to a Sidekiq job. I saw the api for perform_bulk and needed to get each id into its own array.
@aaronkelton that's nice to know this answer has helped in an actual practical situation; the Ruby language is great!
2
a.map { |s| Array(s) }

or

a.map { |s| [s] }

3 Comments

["a", "b", "c"].map &Kernel.method(:Array)
@mudasobwa Or since Kernel is mixed into everything so that we can pretend to have functions: ["a", "b", "c"].map &method(:Array)
Unexciting, but 99% of Rubiests would elect your #2.
2

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

Comments

0

Interesting that you can use Array#zip to do this. I did not realize #zip worked at all without an argument. Ruby always has a new trick up its sleeve.

Not that this is any better, but it might be a bit more intuitive:

>> ["a", "b", "c"].each_slice(1).to_a
=> [["a"], ["b"], ["c"]]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.