diff options
| author | Jun Hiroe <[email protected]> | 2014-03-22 13:46:53 +0900 |
|---|---|---|
| committer | Jun Hiroe <[email protected]> | 2014-03-22 14:51:45 +0900 |
| commit | af7db89aa3630264c64da638c6330160c99d94b8 (patch) | |
| tree | 69dbb36d80af0129f3cd2d835aaf51fa48b4f3df | |
| parent | 7c82b9e1bfffa6b703dc2f4a161b01e37f9154bc (diff) | |
| download | mruby-af7db89aa3630264c64da638c6330160c99d94b8.tar.gz mruby-af7db89aa3630264c64da638c6330160c99d94b8.zip | |
Add Enumerable#max_by
| -rw-r--r-- | mrbgems/mruby-enum-ext/mrblib/enum.rb | 35 | ||||
| -rw-r--r-- | mrbgems/mruby-enum-ext/test/enum.rb | 4 |
2 files changed, 39 insertions, 0 deletions
diff --git a/mrbgems/mruby-enum-ext/mrblib/enum.rb b/mrbgems/mruby-enum-ext/mrblib/enum.rb index d0e125850..e61062e3f 100644 --- a/mrbgems/mruby-enum-ext/mrblib/enum.rb +++ b/mrbgems/mruby-enum-ext/mrblib/enum.rb @@ -267,4 +267,39 @@ module Enumerable ary end alias collect_concat flat_map + + ## + # call-seq: + # enum.max_by {|obj| block } -> obj + # enum.max_by -> an_enumerator + # + # Returns the object in <i>enum</i> that gives the maximum + # value from the given block. + # + # If no block is given, an enumerator is returned instead. + # + # %w[albatross dog horse].max_by { |x| x.length } #=> "albatross" + + def max_by(&block) + return to_enum :max_by unless block_given? + + first = true + max = nil + max_cmp = nil + + self.each do |val| + if first + max = val + max_cmp = block.call(val) + first = false + else + if cmp = block.call(val) > max_cmp + max = val + max_cmp = cmp + end + end + end + + max + end end diff --git a/mrbgems/mruby-enum-ext/test/enum.rb b/mrbgems/mruby-enum-ext/test/enum.rb index 664c1b344..bca1fc4f6 100644 --- a/mrbgems/mruby-enum-ext/test/enum.rb +++ b/mrbgems/mruby-enum-ext/test/enum.rb @@ -76,3 +76,7 @@ assert("Enumerable#flat_map") do assert_equal [1, -1, 2, -2, 3, -3, 4, -4], [1, 2, 3, 4].flat_map { |e| [e, -e] } assert_equal [1, 2, 100, 3, 4, 100], [[1, 2], [3, 4]].flat_map { |e| e + [100] } end + +assert("Enumerable#max_by") do + assert_equal "albatross", %w[albatross dog horse].max_by { |x| x.length } +end |
