Quantcast

How to Combo

classic Classic list List threaded Threaded
6 messages Options
Reply | Threaded
Open this post in threaded view
|  
Report Content as Inappropriate

How to Combo

trans
Easiest implementation of "some_method" in Ruby?

     a = %w|a b|
     b = %w|a x|
     c = %w|x y|

  some_method(a,b,c)

  #=>

   [ ["a", "a", "x"]
     ["a", "a", "y"]
     ["a", "x", "x"]
     ["a", "x", "y"]
     ["b", "a", "x"]
     ["b", "a", "y"]
     ["b", "x", "x"]
     ["b", "x", "y"] ]
  
Order doesn't really matter.

Reply | Threaded
Open this post in threaded view
|  
Report Content as Inappropriate

Re: How to Combo

Harry Kakueki
On Sun, Dec 25, 2011 at 10:27 PM, Intransition <[hidden email]> wrote:

> Easiest implementation of "some_method" in Ruby?
>
>      a = %w|a b|
>      b = %w|a x|
>      c = %w|x y|
>
>   some_method(a,b,c)
>
>   #=>
>
>    [ ["a", "a", "x"]
>      ["a", "a", "y"]
>      ["a", "x", "x"]
>      ["a", "x", "y"]
>      ["b", "a", "x"]
>      ["b", "a", "y"]
>      ["b", "x", "x"]
>      ["b", "x", "y"] ]
>
> Order doesn't really matter.
>

This seems to do it.
I don't have time now to try something better.

Hope it helps.

def some_method(a,b,c)
  [].tap{|w| a.each{|x| b.each{|y| c.each{|z| w << [x,y,z]}}}}
end


Harry

Reply | Threaded
Open this post in threaded view
|  
Report Content as Inappropriate

Re: How to Combo

Bartosz Dziewoński
def some_method(a,b,c)
  a.product(b, c)
end

I think it only works on 1.9.

-- Matma Rex

Reply | Threaded
Open this post in threaded view
|  
Report Content as Inappropriate

Re: How to Combo

trans
Ah, that's what I had over looked... the product! 

Thank you.
Reply | Threaded
Open this post in threaded view
|  
Report Content as Inappropriate

Re: How to Combo

Brian Candler
In reply to this post by trans
Thomas Sawyer wrote in post #1038150:

> Easiest implementation of "some_method" in Ruby?
>
>      a = %w|a b|
>      b = %w|a x|
>      c = %w|x y|
>
>   some_method(a,b,c)
>
>   #=>
>
>    [ ["a", "a", "x"]
>      ["a", "a", "y"]
>      ["a", "x", "x"]
>      ["a", "x", "y"]
>      ["b", "a", "x"]
>      ["b", "a", "y"]
>      ["b", "x", "x"]
>      ["b", "x", "y"] ]
>
> Order doesn't really matter.

Does some_method only accept exactly three arguments?
Is each argument an array of exactly two elements?

--
Posted via http://www.ruby-forum.com/.

Reply | Threaded
Open this post in threaded view
|  
Report Content as Inappropriate

Re: How to Combo

trans
On Monday, December 26, 2011 4:36:26 AM UTC-5, Brian Candler wrote:

Does some_method only accept exactly three arguments?
Is each argument an array of exactly two elements?


Yes, Good questions. I should have made it clear this was an arbitrary example and any number of arguments, each with any number of elements ought to work too.

Thankfully, the simple solution, which I was pretty sure was there but couldn't recall, was presented: Ruby has Array#product.

Loading...