Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions spec/std/hash_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -923,6 +923,29 @@ describe "Hash" do
h2.should eq({"1a" => "a", "2b" => "b", "3c" => "c"})
end

describe "transform_keys!" do
it "transforms keys in place" do
h = {1 => "a", 2 => "b", 3 => "c"}

h.transform_keys! { |x| x + 1 }.should be(h)
h.should eq({2 => "a", 3 => "b", 4 => "c"})
end

it "does nothing when empty hash" do
h = {} of Int32 => String

h.transform_keys! { |x| x + 1 }
h.should be_empty
end

it "transforms keys with values included" do
h = {"1" => "a", "2" => "b", "3" => "c"}

h.transform_keys! { |k, v| "#{k}#{v}" }
h.should eq({"1a" => "a", "2b" => "b", "3c" => "c"})
end
end

it "transforms values" do
h1 = {"a" => 1, "b" => 2, "c" => 3}

Expand Down
18 changes: 18 additions & 0 deletions src/hash.cr
Original file line number Diff line number Diff line change
Expand Up @@ -1755,6 +1755,24 @@ class Hash(K, V)
end
end

# Destructively transforms all keys using a block. Same as transform_keys but modifies in place.
# The block cannot change a type of keys.
# The block yields the key and value.
#
# ```
# hash = {"a" => 1, "b" => 2, "c" => 3}
# hash.transform_keys! { |key| key.upcase }
# hash # => {"A" => 1, "B" => 2, "C" => 3}
# hash.transform_keys! { |key, value| key * value }
# hash # => {"a" => 1, "bb" => 2, "ccc" => 3}
# ```
def transform_keys!(&block : K, V -> K) : self
transformed_hash = self.transform_keys(&block)
initialize_dup_entries(transformed_hash) # we need only to copy the buffer
initialize_copy_non_entries_vars(transformed_hash)
self
end
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It probably makes sense to move the copying logic into a new method #replace, similar to Hash#replace in Ruby.


# Returns a new hash with the results of running block once for every value.
# The block can change a type of values.
# The block yields the value and key.
Expand Down