2

I need to turn an array of integers like [1,2,3] into an array in which the integers are each followed by a zero: [1,0,2,0,3,0].

My best guess, which works but looks jenky:

> [1,2,3].flat_map{|i| [i,0]} => [1,0,2,0,3,0]
2
  • 2
    imo, flat_map is ideal. It's efficient and reads well. Had you not mentioned it I would have given it as an answer. btw, your question is only implied. Best to always state the question. Commented Mar 9, 2017 at 6:04
  • [i, 0] expresses "integers are each followed by a zero" pretty well. Commented Mar 9, 2017 at 8:00

3 Answers 3

5

While Array#zip works pretty well, one might avoid the pre-creation of zeroes array by using Array#product:

[1,2,3].product([0]).flatten

or, just use a reducer:

[1,2,3].each_with_object([]) { |e, acc| acc << e << 0 }
Sign up to request clarification or add additional context in comments.

Comments

3

Pretty straight forward with zip:

a = (1..10).to_a

b = Array.new(a.length, 0)

a.zip(b).flatten
# => [1, 0, 2, 0, 3, 0, 4, 0, 5, 0, 6, 0, 7, 0, 8, 0, 9, 0, 10, 0]

4 Comments

You should inline b, imo.
When I see Array.new construct I always fear that I suddenly woke up in javascript land :) b = [0] * a.size?
@mudasobwa JavaScript's new Array() and that one is far more unpredictable as new Array(10) is an array of length 10, while new Array (10, 11) is a two element array. The Ruby one is more consistent: Array.new(size=0, default=nil)
b = [0].cycle
0

This seems same as yours -))

[1,2,3].map {|i| [i, 0] }.flatten

Also this.

 [1,2,3].collect {|x| [x, 0] }.flatten

Ugly and uneffective solution.

 [1,2,3].join("0").split("").push(0).map{|s| s.to_i }

1 Comment

map in an alias for collect, that said first two are exactly same. The latter won’t work for 2-digits numbers.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.