JesusJPG
JesusJPG

Reputation: 45

Is there an easy way to multiply an array and a integer in ruby?

I need to repeat a certain set of items inside an array.

I need something like this in Python:

["a","b"] * 3
# result: ["a","b","a","b","a","b"]

I tried doing the same way, but I am getting:

(erb):329:in `*': Array can't be coerced into Integer (TypeError)

Is there an easy way to solve it?

Edit: Already solved. It seems to happen that it works when it is done like this

["a", "b"] * 2

But does not work backwards:

2 * ["a", "b"]

Upvotes: 0

Views: 73

Answers (2)

Eric Duminil
Eric Duminil

Reputation: 54223

A * B is not always B * A

3 * 4 means:

3 repeated 4 times.

4 * 3 means:

4 repeated 3 times.

["a", "b"] * 3 means:

["a", "b"] repeated 3 times.

But what would

3 repeated ["a", "b"] times.

mean? How can you do anything ["a", "b"] times?

In Python

In Python, both are allowed:

["a","b"] * 3
3 * ["a","b"]

and return:

['a', 'b', 'a', 'b', 'a', 'b']

but the second looks sloppy IMHO.

Upvotes: 2

mrzasa
mrzasa

Reputation: 23307

Well, it works in my Ruby 2.5:

["a","b"] * 3
# => ["a", "b", "a", "b", "a", "b"]  

ary * int → new_ary

Repetition — (...) returns a new array built by concatenating the int copies of self. Docs

Upvotes: 4

Related Questions