55
39

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

ブロックについてのあれこれ

Posted at

break, next, return

  • next: 以降は実行せず、次のループを開始
  • break: ループを抜ける。
  • return: メソッドを抜ける

JavaScriptでいうと、next は continue に相当。
return するとブロックを抜けて、メソッドも抜けることに注意。

def block_next
  puts '----'
  (1..5).each do |i|
    next if i % 3 == 0
    puts i
  end
  puts 'end'
end

def block_break
  puts '----'
  (1..5).each do |i|
    break if i % 3 == 0
    puts i
  end
  puts 'end'
end

def block_return
  puts '----'
  (1..5).each do |i|
    return if i % 3 == 0
    puts i
  end
  puts 'end'
end

block_next
block_break
block_return

出力結果

----
1
2
4
5
end
----
1
2
end
----
1
2

ブロックの戻り値を指定する

break に引数を指定したら、ブロックの戻り値になる。

1.tap {|i| break i+1}
# => 2

1.tap {|i| }
# => 1
55
39
0

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
55
39

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?