自分にやさしく学ぶプログラミング

プログラミング学習記録、備忘録

Ruby: eachとmapの返り値

概要

eachとmapの使い分けがようやく実感として掴めた気がした。 返り値が違う。

eachの返り値

eachは繰り返し処理を実行したオブジェクトを返す。

          ary = ["./hello/11", "./hello/22", "./hello/33"]
          test = []
          ary.each { |a| test << a.delete_prefix("./hello/") }
                # => ["./hello/11", "./hello/22", "./hello/33"]
          test
                # => ["11", "22", "33"]

mapの返り値

mapは繰り返し処理をした結果を返す。

          ary = ["./hello/11", "./hello/22", "./hello/33"]
          test = []
          ary.map { |a| test << a.delete_prefix("./hello/") }
                # => [["11", "22", "33"], ["11", "22", "33"], ["11", "22", "33"]]
          test
                # => ["11", "22", "33"]

結局何だ

上のように繰り返しの結果を得たいのであればこんな感じでmap使うのがいい。

      ary = ["./hello/11", "./hello/22", "./hello/33"]
      test = ary.map { |a| a.delete_prefix("./hello/") }
            # => ["11", "22", "33"]