如何从Ruby中的数组元素创建一个组合数组

时间:2014-04-06 03:33:45

标签: ruby arrays

我有以下数组。

@arr = ["A:c,b,a", "B:a,b,d", "C:a,c,b", "D:d,a,c", "a:A,C,D", "b:D,A,B", "c:B,A,C", "d:D,C,A"] 

我想创建一个数组,其中包含之前和之后的字母组合:。

输出

["Ac,Ab,Aa", "Ba,Bb,Bd", "Ca,Cc,Cb", "Dd,Da,Dc", "aA,aC,aD", "bD,bA,bB", "cB,cA,cC", "dD,dC,dA"]

我尝试过以下操作,但它出错了。

@arr.each { |item| name, choices =item.split(':')
            @names<<name
            @choices<<choices.strip
}
@combi = @name.product(@choices)

我感谢任何投入。我提前谢谢你。

======

完整代码

soshisoai.rb

class Soshisoai

  attr_reader :names, :choices, :arr, :combi

  def initialize 
    @arr=[]
    @names=[]
    @choices=[]
    file = File.new('soshisoai.txt', "r")
    file.each_line{|line| @arr<< line.strip }
    @arr.each { |item| name, choices =item.split(':')
                @names<<name
                @choices<<choices.strip
    }
    @combi = @name.product(@choices)

  end

end

soshisoai_spec.rb

require './spec_helper'
require './soshisoai.rb'

describe Soshisoai do

  specify{ expect(Soshisoai.new().arr).to eq ["A:c,b,a", "B:a,b,d", "C:a,c,b", "D:d,a,c", "a:A,C,D", "b:D,A,B", "c:B,A,C", "d:D,C,A"] }    
  specify{ expect(Soshisoai.new().names).to eq ["A", "B", "C", "D", "a", "b", "c", "d"] }
  specify{ expect(Soshisoai.new().choices).to eq ["c,b,a", "a,b,d", "a,c,b", "d,a,c", "A,C,D", "D,A,B", "B,A,C", "D,C,A"] }
  specify{ expect(Soshisoai.new().combi).to eq ["Ac,Ab,Aa", "Ba,Bb,Bd", "Ca,Cc,Cb", "Dd,Da,Dc", "aA,aC,aD", "bD,bA,bB", "cB,cA,cC", "dD,dC,dA"] }

end

soshisoai.txt

A:c,b,a
B:a,b,d
C:a,c,b
D:d,a,c
a:A,C,D
b:D,A,B
c:B,A,C
d:D,C,A

2 个答案:

答案 0 :(得分:1)

是的,您可以使用Array#product

<强>代码

@arr.map { |str| lead, rest = str.split(':');
  [lead].product(rest.split(',')).map(&:join).join(',') } 

<强>解释

@arr = ["A:c,b,a", "B:a,b,d", "C:a,c,b", "D:d,a,c",
        "a:A,C,D", "b:D,A,B", "c:B,A,C", "d:D,C,A"]

map首先将"A:c,b,a"传递给块,并将其分配给块变量:

str = "A:c,b,a"
lead, rest = str.split(':')
  #=> ["A", "c,b,a"]

所以lead => "A"rest => "c,b,a"

rest.split(',')
  #=> ["c", "b", "a"]

所以

a = ["A"].product(["c", "b", "a"])
  #=> [["A", "c"], ["A", "b"], ["A", "a"]]

b = a.map(&:join)
  #=> ["Ac", "Ab", "Aa"]  

b.join(',')
  #=> "Ac,Ab,Aa"

在对@arr的每个其他元素执行类似的计算后,我们得到:

@arr.map { |str| lead, rest = str.split(':');
  [lead].product(rest.split(',')).map(&:join).join(',') } 
  #=> ["Ac,Ab,Aa", "Ba,Bb,Bd", "Ca,Cc,Cb", "Dd,Da,Dc",
  #    "aA,aC,aD", "bD,bA,bB", "cB,cA,cC", "dD,dC,dA"]

答案 1 :(得分:0)

@arr.each_with_object([]){|e, o| lhsStr, rhsStr = e.split(":");
o << rhsStr.split(",").map{|c| lhsStr + c}.join(",")}

#=> ["Ac,Ab,Aa", "Ba,Bb,Bd", "Ca,Cc,Cb", "Dd,Da,Dc",
     "aA,aC,aD", "bD,bA,bB", "cB,cA,cC", "dD,dC,dA"]