summaryrefslogtreecommitdiffhomepage
path: root/mrbgems/mruby-hash-ext/mrblib
diff options
context:
space:
mode:
authorYukihiro "Matz" Matsumoto <[email protected]>2017-07-14 15:13:41 +0900
committerYukihiro "Matz" Matsumoto <[email protected]>2017-07-14 15:13:41 +0900
commitde3edcc17044cfb9e85593236f29424eae46b098 (patch)
tree706c283928a03867f06b5be4a6d5fc9004121673 /mrbgems/mruby-hash-ext/mrblib
parentbad807e7f072553b8e055c1c90baf60f181d718f (diff)
downloadmruby-de3edcc17044cfb9e85593236f29424eae46b098.tar.gz
mruby-de3edcc17044cfb9e85593236f29424eae46b098.zip
Add `Hash#transform_{keys,values}` to `mruby-hash-ext`.
Diffstat (limited to 'mrbgems/mruby-hash-ext/mrblib')
-rw-r--r--mrbgems/mruby-hash-ext/mrblib/hash.rb39
1 files changed, 39 insertions, 0 deletions
diff --git a/mrbgems/mruby-hash-ext/mrblib/hash.rb b/mrbgems/mruby-hash-ext/mrblib/hash.rb
index 31ff6d685..d3b4f6e86 100644
--- a/mrbgems/mruby-hash-ext/mrblib/hash.rb
+++ b/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