合并哈希和密钥都得到,旧的和新的价值观 [英] Merge Hashes and key gets both, old and new values

查看:139
本文介绍了合并哈希和密钥都得到,旧的和新的价值观的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

想象我有一个这样的数组

Imagine I have an array like this

array = [4,"hello",[[3],:d,7,[:a,"seven"]]]



class Array
  def deep_collect_by_elem_type_as_hash()
    e = {}
    self.each(){|x|
      if x.is_a?(Array)
        e.merge(x.deep_collect_by_elem_type_as_hash)
      end
      if !x.is_a?(Array)
        if e.has_key?(x.class)
          e[x.class]<<x
        else
          e[x.class] = [x]
        end
      end
    }
    return e
  end

我想我所有的阵列来创建一个散列,其中有包含不同的类,都在我的数组键。
它们的值将是为每个类的实际的元件。

I want all my arrays to create an hash in which there are keys containing the different classes that are in my Array. Their values will be the actual elements for each class.

因此​​,这将是这样的:

So it would look like this:

{Fixnum=>[4, 3, 7], String=>["hello", "seven"], Symbol=>[:d, :a]}

我要解决整个事情,而无需使用扁平化,做起来recrusive。
特变平的解决办法是这样的:

I want to solve the whole thing without using flatten, but doing it recrusive. Te flatten solution could look like this:

def deep_collect_by_elem_type_as_hash1()
    e = {}
    flat= self.flatten()
    flat.each(){|x|
      if e.has_key?(x.class)
        e[x.class]<<x
      else
        e[x.class] = [x]
      end
    }
    return e
  end

对于那些想知道为什么我不希望使用压平:我仍然有问题,完全理解如何实现递归方法,因此,这是一个问题,给我一个更好的了解。

For those wondering why I do not want to use flatten: I still have problems fully understanding how to implement recursive methods, and therefore this is a question to give me a better understanding.

我想我无论如何都必须实现与块合并,但我想不出一个适当的块。 合并(x.deep_collect_by_elem_type_as_hash(){| K,V1,V2 |帮助}

I think I somehow have to implement merge with a block, but I cannot figure out a proper block. merge(x.deep_collect_by_elem_type_as_hash(){|k,v1,v2| help}

推荐答案

在这里我们去:

a = [4,"hello",[[3],:d,7,[:a,"seven"]]]

def stuff(a)
  res = {}
  a.each do |e|
    if e.is_a?(Array)
      stuff(e).each do |k,v|
        res[k] ||= []
        v.each {|x| res[k] << x}
      end
    else
      k = e.class
      res[k] ||= []
      res[k] << e
    end
  end
  res
end

puts stuff(a).inspect

如果您需要打开和扩展阵列,你可以做线沿线的东西:

if you need to open and extend array, you can do something along the lines of:

class Array
  def stuff(a = self)
  ...
  end
end

这篇关于合并哈希和密钥都得到,旧的和新的价值观的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆