在Crystal中使用不同的键值对合并散列

所以我有各种哈希值,它们并不总是具有相同的键/值对 . 我想要做的是能够合并散列,但是如果它们不存在于该散列中,则添加空键/值对,但在其他散列中也是如此 . 这很难解释,但这可能会更好地解释它:

t1 = Merger.new({"a" => "1"})
puts t1.merge({:b => 2})
# => {"a" => "1", :b => 2}

t2 = Merger.new({"a" => "1", :b => 2})
puts t2.merge({:c => "3"})
# => {"a" => "1", :b => 2, :c => "3"}

t3 = Merger.new({"a" => "1", "b" => 2})
puts t3.merge
# => {"a" => "1", "b" => 2}

t4 = Merger.new
puts t4.merge({:a => 1})
# => {:a => 1}

t5 = Merger.new
puts t4.merge
# => {}

Merger 类实现:

class Merger
  alias AnyHash = Hash(Symbol | String, Int32 | String) |
                  Hash(Symbol, Int32 | String) |
                  Hash(String, Int32 | String) |
                  Hash(String, String) |
                  Hash(String, Int32) |
                  Hash(Symbol, String) |
                  Hash(Symbol, Int32)

  def initialize(params : AnyHash? = nil)
    @params = params
  end

  def merge(other = {} of String => String)
    @params.try do |params|
      other = params.merge(other)
    end
    return other
  end
end

https://play.crystal-lang.org/#/r/3oeh

从字面上看,我应该创建具有键/值对的所有可能组合的联合类型 . 否则,将给出编译时错误 .

是否有更优雅的方式使其工作?

回答(1)

2 years ago

Hash#merge 已经为您找出了正确的泛型类型参数 .

如果我理解正确的话,唯一的问题是将其存储在实例变量中 . 这可以使 Merger 成为一个泛型类,其中类型是从构造函数参数自动推断出来的:

class Merger(T)
  def self.new
    new({} of String => String)
  end

  def initialize(@params : T)
  end

  def merge(other = {} of String => String)
    @params.merge(other)
  end
end