【Ruby】map、map! メソッドの自作。破壊的メソッドの作り方
そういえば、非破壊的・破壊的なメソッドの複数実装ってしたことない。
やってみよう。
#DIY means Do It Yourself class Array def map_DIY!(&b) self.each_with_index do |item, i| self[i] = b.call(item) end end def map_DIY(&b) copy = self.dup copy.map_DIY!(&b) end end a = [1,2,3] b = a.map_DIY{|x| x**x} p a p b a.map_DIY!{|x| x**x} p a
■実行結果
[1, 2, 3] [1, 4, 27] [1, 4, 27]
なるほど。