2
0

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.

Rubyのyieldと多重ブロック構文にnextとbreakを使った結果

Posted at

ブロックの中にブロックを作ってyieldしてnextしてみる

next.rb
hoges = [ "hoge", "hogehoge", "hogehogehoge" ]

count = 0

def updown
  p "up"
  yield
  p "down"
end

hoges.each do |hoge|
  updown do
    count += 1
    if count == 2
      p 123456789
      next
    else
      puts "#{count} : #{hoge}"
    end
  end
end
出力結果
"up"
1 : hoge
"down"
"up"
123456789
"down"
"up"
3 : hogehogehoge
"down"

ブロックの中にブロックを作ってyieldしてbreakしてみる

break.rb
hoges = [ "hoge", "hogehoge", "hogehogehoge" ]

count = 0

def updown
  p "up"
  yield
  p "down"
end

hoges.each do |hoge|
  updown do
    count += 1
    if count == 2
      p 123456789
      break
    else
      puts "#{count} : #{hoge}"
    end
  end
end
出力結果
"up"
1 : hoge
"down"
"up"
123456789
"up"
3 : hogehogehoge
"down"
2
0
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
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?