Forum: Ruby Kind of Array "product" question

8e16f7669af5b4ecfa4f2b89f32b21b6?d=identicon&s=25 Stefan Salewski (Guest)
on 2013-11-09 21:04
(Received via mailing list)
I am cleaning up my code, which I wrote in the last months...
I have code like this:

irb(main):053:0* a = ['a', 'b', 'c']
=> ["a", "b", "c"]
irb(main):054:0> b = [1, 2]
=> [1, 2]
irb(main):055:0> a.map{|el| [el, *b]}
=> [["a", 1, 2], ["b", 1, 2], ["c", 1, 2]] # (*)

The result is what I desire, but I had the feeling that this is not the
most elegant and fastest way, because it iterates over each element in
a. Is there a better solution to replace a.map... with?

I searched in the array documentation, but only found

irb(main):058:0> a.product([b])
=> [["a", [1, 2]], ["b", [1, 2]], ["c", [1, 2]]]

which is not really what I desire. Related question: What is the best
way to convert the double nested array above into (*) at the top?

Or can we write the following in a simpler form, without double array
indices?

a.product([b]).each{|el| c = el[0]; x = el[1][0]; y = el[1][1]; puts c,
x, y}

Best regards,

Stefan Salewski
Aa082c8b00a50928e5860dcd70bf2368?d=identicon&s=25 tamouse m. (tamouse_m)
on 2013-11-10 02:26
(Received via mailing list)
On Nov 9, 2013, at 2:02 PM, Stefan Salewski <mail@ssalewski.de> wrote:

> The result is what I desire, but I had the feeling that this is not the
> most elegant and fastest way, because it iterates over each element in
> a. Is there a better solution to replace a.map... with?
>
> I searched in the array documentation, but only found
>
> irb(main):058:0> a.product([b])
> => [["a", [1, 2]], ["b", [1, 2]], ["c", [1, 2]]]

Simple one for this:

a.product([b]).map(&:flatten)

Still not elegant.
Please log in before posting. Registration is free and takes only a minute.
Existing account

NEW: Do you have a Google/GoogleMail, Yahoo or Facebook account? No registration required!
Log in with Google account | Log in with Yahoo account | Log in with Facebook account
No account? Register here.