LoginSignup
3
2

More than 3 years have passed since last update.

rubyのmap関数ではreturnではなくnextをつかう

Last updated at Posted at 2020-01-25

rubyで以下の様なコードを実行しようとして失敗した話

def hoge()
  (1..5).map do |i|
    return 'this is 3' if i == 3
    #~ 複雑な処理 ~
    i
  end
end

p hoge # => "this is 3"

なんとなく上記のようなコードを実行したらmapの結果は[1, 2, 'this is 3', 4, 5]の配列がかえってくると思っていたけど実際には"this is 3"が返ってきたので、慌ててrubyのドキュメントを読んでたら、nextを使う必要があるみたい。
nextも引数を取れるので、条件式が正(true)の時に返したいデータをnextの引数に渡す様にしてあげる。

つまり以下の様にするのが正しい。

def hoge()
  (1..5).map do  |i|
    next 'this is 3' if i  == 3
    #~ 複雑な処理 ~
    i
  end
end

p hoge # => [1, 2, 'this is 3', 4, 5]

あやうくバグを仕込むことになった…

ちなみにJavaScriptとか他の言語ではreturnが多いからrubyもreturnだと思ってた。

var arr = [1, 2, 3, 4, 5];
map_arr = arr.map(i => {
    if (i == 3) {
        return 'this is 3';
    }
    // ~ 複雑な処理 ~
    return i
})

console.log(map_arr) // [ 1, 2, 'this is 3', 4, 5 ]
3
2
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2