From f1a04dae3e68e70218dd70f24c4f4bfaea995092 Mon Sep 17 00:00:00 2001 From: "Yukihiro \"Matz\" Matsumoto" Date: Wed, 3 Jul 2024 07:31:32 +0900 Subject: [PATCH] mruby-enum-ext (sort_by): avoid copying the receiver When the receiver is an Array. --- mrbgems/mruby-enum-ext/mrblib/enum.rb | 28 +++++++++++++++------------ 1 file changed, 16 insertions(+), 12 deletions(-) diff --git a/mrbgems/mruby-enum-ext/mrblib/enum.rb b/mrbgems/mruby-enum-ext/mrblib/enum.rb index a4380d6ca..0848ab9f6 100644 --- a/mrbgems/mruby-enum-ext/mrblib/enum.rb +++ b/mrbgems/mruby-enum-ext/mrblib/enum.rb @@ -189,20 +189,9 @@ module Enumerable # values in enum through the given block. # # If no block is given, an enumerator is returned instead. - def sort_by(&block) return to_enum :sort_by unless block - - ary = [] - orig = [] - self.each_with_index{|e, i| - orig.push(e) - ary.push([block.call(e), i]) - } - if ary.size > 1 - ary.sort! - end - ary.collect{|e,i| orig[i]} + self.to_a.sort_by(&block) end ## @@ -892,3 +881,18 @@ module Enumerable result end end + +class Array + def sort_by(&block) + return to_enum :sort_by unless block + + ary = [] + self.each_with_index{|e, i| + ary.push([block.call(e), i]) + } + if ary.size > 1 + ary.sort! + end + ary.collect!{|e,i| self[i]} + end +end