新手问题 两个 array 合并成 iterator hash

luffycn · 2014年12月05日 · 最后由 luffycn 回复于 2014年12月09日 · 3507 次阅读

one = ['a', 'b', 'c'] two = ['A', 'B', 'C']

想合并成 [ 0 => {:one => 'a', :two => 'A'}, 1 => {:one => 'b', :two => 'B'}, 2 => {:one => 'c', :two => 'C'}, ]

有没有什么快捷的办法

one.zip(two).map{|one,two| {one:one,two:two}}

#或者
one.zip(two).map{|one,two| {one:one,two:two}}
  .each_with_index.map{|e,i| {i=>e}}.reduce({},&:merge)

#或者
Hash[*one.zip(two).map{|one,two| {one:one,two:two}}.each_with_index.to_a.map(&:reverse).flatten]

#或者
one.zip(two).reduce({}) do |res, zp|
  one,two = zp
  i = res.size
  res.merge!(i=>{one:one,two:two})
end

@davidhuangdw 如果不确定要合并的数组的个数该如何处理了, 比如,有可能是

one = ['a', 'b', 'c'] two = ['A', 'B', 'C'] 需要合并

也有可能是

one = ['a', 'b', 'c'] two = ['A', 'B', 'C'] three=['m', 'n', 'k', 'h']

#2 楼 @luffycn 输入是什么样的呢?keys 是给定的吗? 变长是 ok 的。假如,输入是 arrys 和 keys:

one = ['a', 'b', 'c']
two = ['A', 'B', 'C']
three=['m', 'n', 'k', 'h']
four=%w(x y )

#假设输入为 arrays, keys:
arrays = [one,two,three,four]
keys = %w{one two three four}
#or
keys = %w{one two three four five six seven ...}.first(arrays.size)

#那么可以这样:
klass = Struct.new(*keys.map(&:to_sym))
objects = arrays.reduce(&:zip).map{|tup| klass.new(*tup.flatten)}.map(&:to_h)

def hash_from_arr(arr)
  arr.reduce({}) do |res, element|
    i = res.size
    res.merge!(i=>element)
  end
end
hash_from_arr(objects)

@davidhuangdw great, 完全达到目的了,thanks so much

需要 登录 后方可回复, 如果你还没有账号请 注册新账号