From de3edcc17044cfb9e85593236f29424eae46b098 Mon Sep 17 00:00:00 2001 From: "Yukihiro \"Matz\" Matsumoto" Date: Fri, 14 Jul 2017 15:13:41 +0900 Subject: Add `Hash#transform_{keys,values}` to `mruby-hash-ext`. --- mrbgems/mruby-hash-ext/mrblib/hash.rb | 39 +++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) (limited to 'mrbgems/mruby-hash-ext/mrblib') 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 -- cgit v1.2.3