0
0

More than 1 year has passed since last update.

Ruby 配列 ブロックについて 3

Last updated at Posted at 2023-07-16

はじめに

学習内容

ブロック

  • with_indexメソッド
  • each_with_indexメソッド

参考にした教材

ブロック

foods = ["ラーメン", "ギョウザ", "チャーハン"]
変数foodsをmap処理しつつ、0〜2の番号を与える

with_indexメソッド 生成時のパラメータに従って、要素にインデックスを添えて繰り返す

puts foods.map.with_index{ |food, f| "#{f}: #{food}" } => 0: ラーメン
1: ギョウザ
2: チャーハン
変数foodsから「メン」を含み、偶数である要素を取り除く

with_indexメソッド 生成時のパラメータに従って、要素にインデックスを添えて繰り返す

puts foods.delete_if.with_index{ |food, f| food.include?("メン") && f.even? } => ギョウザ, チャーハン
変数foodsの各要素に0〜2の番号を与える

each_with_indexメソッド 要素とそのインデックスをブロックに渡して繰り返す

puts foods.each_with_index { |food, f| puts "#{f}: #{food}" } => 0: ラーメン
1: ギョウザ
2: チャーハン

補足
どちらもデータを1つずつ取り出すことはできるが、位置情報を使いたい場合は「with_index」を使うべき。実際に、「each_with_index」では、

foods.each_with_index(1) { |food, f| puts "#{f}: >#{food}" }

=> ArgumentError

となり、任意の位置情報を与えられない。
一方で、「with_index」なら、

foods.each.with_index(1) { |food, f| puts "#{f}: #{food}" }

=> 1: ラーメン 2: ギョウザ 3: チャーハン

と位置情報も与えられる。

まとめ

  • with_indexは任意の位置情報を与えられる
  • ブロックパラメータの第2引数も上手く使っていきたい

⚠️学習4ヶ月目の初学者による投稿です。
⚠️間違いがあるかもしれません。ご容赦ください。
⚠️ご指導、ご教授いただけると幸いです。

0
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
0
0