1
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のブロック 色々試してみた

Last updated at Posted at 2018-09-30

Rubyのブロックは、苦手意識があったので「プロを目指す人のためのRuby入門」を参考に、色々コードを打ってみた。

yieldでブロックの処理を呼び出す

def sports
  puts 'サッカー'
  yield
  puts '野球'
end

sports do
  puts 'バスケ'
end

結果

サッカー
バスケ
野球

def sports内のyieldのところでsports do 〜 end内部の処理が呼び出される。

ブロックに引数を渡す(1)

def sports
  puts 'サッカー'
  yield 'バスケ'
  puts '野球'
end

sports do |sport|
  puts "#{sport}がしたいです"
end

結果

サッカー
バスケがしたいです
野球

yieldでバスケを引数としてブロックに渡し、ブロックがブロック変数sportで受ける。変数sportと式展開で合体させた文字をブロック内で出力させる処理をすると、yieldのところで実行される。

ブロックに引数を渡す(2)

def sports
  puts 'サッカー'
  message = yield 'バスケ'
  puts message
  puts '野球'
end

sports do |sport|
  "#{sport}がしたいです"
end

結果

サッカー
バスケがしたいです
野球

ブロック内の"#{sport}がしたいです"と言う処理を、メソッド内でローカル変数messageに一旦代入し、それからputsで出力している。

こんなやり方も(1)

def sports
  sports_comics = ['キャプテン翼', 'SLUM DUNK', 'MAJOR']
  yield sports_comics
end

sports do |sports_comics|
  sports_comics.each {|comic| puts "#{comic}を読もう!"}
end

結果

キャプテン翼を読もう!
SLUM DUNKを読もう!
MAJORを読もう!

こんなやり方も(2)

def comics
  sport = '野球'
  comics = ['MAJOR', 'ドカベン', 'ROOKIES']
  yield sport, comics
end

comics do |sport, comics|
  puts "#{sport}の漫画と言えば#{comics.join('、')}でしょう!"
end

結果

野球の漫画と言えばMAJOR、ドカベン、ROOKIESでしょう!

自分で色々やってみないと、説明を読んだだけではよく分からない。

1
0
1

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
1
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?