Add `Hash#transform_{keys,values}` to `mruby-hash-ext`.
MODIFY
mrbgems/mruby-hash-ext/mrbgem.rake
mrbgems/mruby-hash-ext/mrbgem.rake
@@ -2,6 +2,7 @@ MRuby::Gem::Specification.new('mruby-hash-ext') do |spec|
spec.license = 'MIT'
spec.author = 'mruby developers'
spec.summary = 'Hash class extension'
- spec.add_dependency 'mruby-enum-ext', :core => 'mruby-enum-ext'
- spec.add_dependency 'mruby-array-ext', :core => 'mruby-array-ext'
+ spec.add_dependency 'mruby-enum-ext', core: 'mruby-enum-ext'
+ spec.add_dependency 'mruby-array-ext', core: 'mruby-array-ext'
+ spec.add_test_dependency 'mruby-enumerator', core: 'mruby-enumerator'
end

MODIFY
mrbgems/mruby-hash-ext/mrblib/hash.rb
mrbgems/mruby-hash-ext/mrblib/hash.rb
@@ -382,4 +382,43 @@ class Hash
n
end
end
+
+ ##
+ # call-seq:
+ # hsh.transform_keys {|key| block } -> new_hash
+ # hsh.transform_keys -> an_enumerator
+ #
+ # Returns a new hash, with the keys computed from running the block
+ # once for each key in the hash, and the values unchanged.
+ #
+ # If no block is given, an enumerator is returned instead.
+ #
+ def transform_keys(&b)
+ return to_enum :transform_keys unless block_given?
+ hash = {}
+ self.each_key do |k|
+ new_key = yield(k)
+ hash[new_key] = self[k]
+ end
+ hash
+ end
+ ##
+ # call-seq:
+ # hsh.transform_values {|value| block } -> new_hash
+ # hsh.transform_values -> an_enumerator
+ #
+ # Returns a new hash with the results of running the block once for
+ # every value.
+ # This method does not change the keys.
+ #
+ # If no block is given, an enumerator is returned instead.
+ #
+ def transform_values(&b)
+ return to_enum :transform_values unless block_given?
+ hash = {}
+ self.each_key do |k|
+ hash[k] = yield(self[k])
+ end
+ hash
+ end
end

MODIFY
mrbgems/mruby-hash-ext/test/hash.rb
mrbgems/mruby-hash-ext/test/hash.rb
@@ -254,3 +254,29 @@ assert("Hash#dig") do
assert_equal(1, h.dig(:a, :b, :c))
assert_nil(h.dig(:d))
end
+
+assert("Hash#transform_keys") do
+ h = {a:{b:{c:1}}}
+ assert_equal(1, h.dig(:a, :b, :c))
+ assert_nil(h.dig(:d))
+end
+
+assert("Hash#transform_keys") do
+ h = {"1" => 100, "2" => 200}
+ assert_equal(h.transform_keys{|k| k+"!"},
+ {"1!" => 100, "2!" => 200})
+ assert_equal(h.transform_keys{|k|k.to_i},
+ {1 => 100, 2 => 200})
+ assert_equal(h.transform_keys.with_index{|k, i| "#{k}.#{i}"},
+ {"1.0" => 100, "2.1" => 200})
+end
+
+assert("Hash#transform_values") do
+ h = {a: 1, b: 2, c: 3}
+ assert_equal(h.transform_values{|v| v * v + 1},
+ {a: 2, b: 5, c: 10})
+ assert_equal(h.transform_values{|v|v.to_s},
+ {a: "1", b: "2", c: "3"})
+ assert_equal(h.transform_values.with_index{|v, i| "#{v}.#{i}"},
+ {a: "1.0", b: "2.1", c: "3.2"})
+end

Add `Hash#transform_{keys,values}` to `mruby-hash-ext`.