Skip to content

Commit

Permalink
Showing 2 changed files with 22 additions and 12 deletions.
30 changes: 20 additions & 10 deletions spec/std/hash_spec.cr
Original file line number Diff line number Diff line change
@@ -1,15 +1,19 @@
require "spec"

alias RecursiveHash = Hash(RecursiveHash, RecursiveHash)
module HashSpec
alias RecursiveHash = Hash(RecursiveHash, RecursiveHash)

class HashBreaker
getter x : Int32
class HashBreaker
getter x : Int32

def initialize(@x)
def initialize(@x)
end
end

class NeverInstantiated
end
end

class NeverInstantiated
alias RecursiveType = String | Int32 | Array(RecursiveType) | Hash(Symbol, RecursiveType)
end

describe "Hash" do
@@ -268,7 +272,7 @@ describe "Hash" do
assert { {1 => 2, 3 => 4}.to_s.should eq("{1 => 2, 3 => 4}") }

assert do
h = {} of RecursiveHash => RecursiveHash
h = {} of HashSpec::RecursiveHash => HashSpec::RecursiveHash
h[h] = h
h.to_s.should eq("{{...} => {...}}")
end
@@ -325,6 +329,12 @@ describe "Hash" do
h3.should eq({1 => 11, 3 => 4, 2 => 8})
end

it "merges recursive type (#1693)" do
hash = {:foo => "bar"} of Symbol => HashSpec::RecursiveType
result = hash.merge({:foobar => "foo"})
result.should eq({:foo => "bar", :foobar => "foo"})
end

it "merges!" do
h1 = {1 => 2, 3 => 4}
h2 = {1 => 5, 2 => 3}
@@ -494,13 +504,13 @@ describe "Hash" do
end

it "fetches from empty hash with default value" do
x = {} of Int32 => HashBreaker
breaker = x.fetch(10) { HashBreaker.new(1) }
x = {} of Int32 => HashSpec::HashBreaker
breaker = x.fetch(10) { HashSpec::HashBreaker.new(1) }
breaker.x.should eq(1)
end

it "does to to_s with instance that was never instantiated" do
x = {} of Int32 => NeverInstantiated
x = {} of Int32 => HashSpec::NeverInstantiated
x.to_s.should eq("{}")
end

4 changes: 2 additions & 2 deletions src/hash.cr
Original file line number Diff line number Diff line change
@@ -494,14 +494,14 @@ class Hash(K, V)
# hash.merge!({"baz": "qux"})
# hash # => {"foo" => "bar", "baz" => "qux"}
# ```
def merge!(other : Hash(K, V))
def merge!(other : Hash)
other.each do |k, v|
self[k] = v
end
self
end

def merge!(other : Hash(K, V), &block : K, V, V -> V)
def merge!(other : Hash, &block)
other.each do |k, v|
if self.has_key?(k)
self[k] = yield k, self[k], v

0 comments on commit 7ee89b5

Please sign in to comment.