diff options
| author | Yukihiro "Matz" Matsumoto <[email protected]> | 2017-07-15 08:51:35 +0900 |
|---|---|---|
| committer | Yukihiro "Matz" Matsumoto <[email protected]> | 2017-07-15 08:51:35 +0900 |
| commit | 515a093213cba06e4750d4facfbd9a8297426478 (patch) | |
| tree | fc99ca4bd3591dc431a2ca2575787a7443cac4b4 /mrbgems/mruby-hash-ext | |
| parent | d7fef24a95e122a5be2b9d0519e57a79fbe5da46 (diff) | |
| download | mruby-515a093213cba06e4750d4facfbd9a8297426478.tar.gz mruby-515a093213cba06e4750d4facfbd9a8297426478.zip | |
Add `Hash#transform_keys!` and `Hash#transform_values`.
Diffstat (limited to 'mrbgems/mruby-hash-ext')
| -rw-r--r-- | mrbgems/mruby-hash-ext/mrblib/hash.rb | 37 | ||||
| -rw-r--r-- | mrbgems/mruby-hash-ext/test/hash.rb | 4 |
2 files changed, 41 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 diff --git a/mrbgems/mruby-hash-ext/test/hash.rb b/mrbgems/mruby-hash-ext/test/hash.rb index 5c08212ce..2ae88c307 100644 --- a/mrbgems/mruby-hash-ext/test/hash.rb +++ b/mrbgems/mruby-hash-ext/test/hash.rb @@ -263,6 +263,8 @@ assert("Hash#transform_keys") do {1 => 100, 2 => 200}) assert_equal(h.transform_keys.with_index{|k, i| "#{k}.#{i}"}, {"1.0" => 100, "2.1" => 200}) + assert_equal(h.transform_keys!{|k|k.to_i}, h) + assert_equal(h, {1 => 100, 2 => 200}) end assert("Hash#transform_values") do @@ -273,4 +275,6 @@ assert("Hash#transform_values") do {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"}) + assert_equal(h.transform_values!{|v|v.to_s}, h) + assert_equal(h, {a: "1", b: "2", c: "3"}) end |
