开发者

How to develop a Ruby array

开发者 https://www.devze.com 2023-03-20 15:43 出处:网络
I have a factorised array of n dimensions and I would like to develop it. Here is an example: develop([:a, :aa]) #=> [[:a, :aa]]

I have a factorised array of n dimensions and I would like to develop it.

Here is an example:

develop([:a, :aa]) #=> [[:a, :aa]]

...which is the same as: [:a].product([:aa]).

Or, more complicated:

develop([:a, [:aa, :bb]]) #=> [[:a, :aa],
                               [:a, :bb]]

I'm working with Ruby 1.9. Thank you for any idea.

Edit:

Another example, with 3 levels of embedded arrays:

develop([:a, [[:b, [:ba, :bb]],
              [:c, [:ca, :cb]],开发者_高级运维
              [:d, [:da, :db]]]]) #=> [[:a, :b, :ba],
                                       [:a, :b, :bb],
                                       [:a, :c, :ca],
                                       [:a, :c, :cb],
                                       [:a, :d, :da],
                                       [:a, :d, :db]]

I wonder if we could use Array's product method (http://ruby-doc.org/core-1.9.3/Array.html#method-i-product), even if we have some embedded arrays.


I'm not sure I fully understand what you are trying to do to these poor arrays, but I managed to make a function that gives the correct output for both the cases you specified. Here is the complete code:

def develop(x)
  return x unless x.is_a? Array
  y = []
  x[1].each do |s|
    d = develop(s)
    d = [d] unless d.is_a? Array
    d.each do |t|
      t = [t] unless t.is_a? Array
      y << [x.first] + t
    end
  end
  return y
end

x = [:a,
        [
            [:b, [:ba, :bb]],
            [:c, [:ca, :cb]],
            [:d, [:da, :db]]
        ]
    ]

p develop(x)

p develop [:a, [:aa, :bb]]

The output is:

C:\Users\David\Documents\scraps\test_ruby>ruby test.rb
[[:a, :b, :ba], [:a, :b, :bb], [:a, :c, :ca], [:a, :c, :cb], [:a, :d, :da], [:a, :d, :db]]
[[:a, :aa], [:a, :bb]]

EDIT 1: Here's a shorter version that also gives the right output:

def develop(x)
  return [x] unless x.is_a? Array
  Array(x.last).collect do |s|
    develop(s).collect do |t|
      [x.first] + Array(t)
    end
  end.flatten 1
end
0

精彩评论

暂无评论...
验证码 换一张
取 消