Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
43
Help us understand the problem. What is going on with this article?
@akkun_choi

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

More than 5 years have passed since last update.

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
43
Help us understand the problem. What is going on with this article?
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away

Comments

No comments
Sign up for free and join this conversation.
Sign Up
If you already have a Qiita account Login
43
Help us understand the problem. What is going on with this article?