rails:对象关系数组映射新数组的更有效方法

时间:2014-04-02 22:00:46

标签: ruby-on-rails ruby arrays mapping

所以数组A基本上是一个关系哈希,我想拉出所有匹配的nums或alphas来创建一个单独的数组,即B和C.

所以一旦我拥有B阵列,我就能立即知道alpha' a'与num:1和2相同 C,我可以马上知道num' 1'有alpha a和b

 A = [{ alpha: 'a', num: '1'},
      { alpha: 'b', num: '1'},
      { alpha: 'a', num: '2'},
      { alpha: 'b', num: '2'}]

 B = [{alpha: 'a', num: [1, 2]},
      {alpha: 'b', num: [1, 2]}]

 C = [{num: '1', alpha: [a, b]},
      {num: '2', alpha: [a, b]}]

到目前为止,我有以下内容,但我认为必须有一种更简单,更有效的方法来实现这一目标。

B = []
C = []

A.each do |datum|
    if !B.any?{|value| value.alpha == datum.alpha}
      temp = {
          alpha: datum.alpha,
          num: (A.map {|value| (value.num == datum.num)? value.num : nil }).compact
      }

      B << temp
    end

    if !C.any?{|value| value.num == datum.num}
      temp = {
          num: datum.num,
          alpha: (A.map {|value| (value.alpha == datum.alpha)? value.alpha : nil }).compact
      }

      C << temp
    end
  end

1 个答案:

答案 0 :(得分:1)

这是诀窍:

a = [
      { alpha: 'a', num: '1'},
      { alpha: 'b', num: '1'},
      { alpha: 'a', num: '2'},
      { alpha: 'b', num: '2'}
    ]

alpha_arry = a.group_by { |h| h[:alpha] }.map do |key,value| 
  {:alpha => key, :num => value.collect { |num_hash| num_hash[:num] }} 
end
alpha_arry
# => [{:alpha=>"a", :num=>["1", "2"]}, {:alpha=>"b", :num=>["1", "2"]}]
num_arry = a.group_by { |h| h[:num] }.map do |key,value| 
  {:num => key, :alpha => value.collect { |alpha_hash| alpha_hash[:alpha] }} 
end
num_arry
# => [{:num=>"1", :alpha=>["a", "b"]}, {:num=>"2", :alpha=>["a", "b"]}]