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

时间:2018-03-06 09:35:10

标签: crystal-lang

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

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 个答案:

答案 0 :(得分:5)

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