summaryrefslogtreecommitdiffhomepage
path: root/mrbgems/mruby-hash-ext/mrblib/hash.rb
diff options
context:
space:
mode:
authorYukihiro "Matz" Matsumoto <[email protected]>2017-07-15 08:51:35 +0900
committerYukihiro "Matz" Matsumoto <[email protected]>2017-07-15 08:51:35 +0900
commit515a093213cba06e4750d4facfbd9a8297426478 (patch)
treefc99ca4bd3591dc431a2ca2575787a7443cac4b4 /mrbgems/mruby-hash-ext/mrblib/hash.rb
parentd7fef24a95e122a5be2b9d0519e57a79fbe5da46 (diff)
downloadmruby-515a093213cba06e4750d4facfbd9a8297426478.tar.gz
mruby-515a093213cba06e4750d4facfbd9a8297426478.zip
Add `Hash#transform_keys!` and `Hash#transform_values`.
Diffstat (limited to 'mrbgems/mruby-hash-ext/mrblib/hash.rb')
-rw-r--r--mrbgems/mruby-hash-ext/mrblib/hash.rb37
1 files changed, 37 insertions, 0 deletions
diff --git a/mrbgems/mruby-hash-ext/mrblib/hash.rb b/mrbgems/mruby-hash-ext/mrblib/hash.rb
index 14da1ddb5..87817f833 100644
--- a/mrbgems/mruby-hash-ext/mrblib/hash.rb
+++ b/mrbgems/mruby-hash-ext/mrblib/hash.rb
@@ -404,6 +404,26 @@ class Hash
end
##
# call-seq:
+ # hsh.transform_keys! {|key| block } -> hsh
+ # hsh.transform_keys! -> an_enumerator
+ #
+ # Invokes the given block once for each key in <i>hsh</i>, replacing it
+ # with the new key returned by the block, and then returns <i>hsh</i>.
+ #
+ # If no block is given, an enumerator is returned instead.
+ #
+ def transform_keys!(&b)
+ return to_enum :transform_keys! unless block_given?
+ self.keys.each do |k|
+ value = self[k]
+ new_key = yield(k)
+ self.__delete(k)
+ self[new_key] = value
+ end
+ self
+ end
+ ##
+ # call-seq:
# hsh.transform_values {|value| block } -> new_hash
# hsh.transform_values -> an_enumerator
#
@@ -421,4 +441,21 @@ class Hash
end
hash
end
+ ##
+ # call-seq:
+ # hsh.transform_values! {|key| block } -> hsh
+ # hsh.transform_values! -> an_enumerator
+ #
+ # Invokes the given block once for each value in the hash, replacing
+ # with the new value returned by the block, and then returns <i>hsh</i>.
+ #
+ # If no block is given, an enumerator is returned instead.
+ #
+ def transform_values!(&b)
+ return to_enum :transform_values! unless block_given?
+ self.keys.each do |k|
+ self[k] = yield(self[k])
+ end
+ self
+ end
end