LoginSignup
2
0

More than 3 years have passed since last update.

【駆け出しWEBエンジニアのためのメモ】each_with_index(Ruby)

Last updated at Posted at 2019-11-03

こんにちは。

Rubyの試験の復習中「each_with_index」と出くわしました。

初見ですが、調べてみるとものすごく使える。

こちら備忘のためのメモです。

よろしければ参考にしていただければ幸いです。

その他、参照させていただいたサイトのリンクも添付しておきます。
感謝です。

eachループで回しつつ、行列内の値に1から番号を振りたい時

with_index doの前に、book内の変数「author,title,price」に値を代入後、行列booksに格納してます(結構端折ってますので、わかりにくい場合は申し訳ないです)

~

book = { author: author, title: title, price: price }

books << book

~



#ここで「each_with_index」を用いて、行列books内のbookに対し1から順に番号を付加してます

books = [ ]

books.each_with_index do |book, index|

  puts "#{index + 1}: #{book[:title]}"

end

 

また「each.with_index」ですと、eachループで回しつつ、行列内の値に指定した番号から順に番号を振ることができるそうです。

10から順に番号を振ってます

books.each.with_index(10) do |book, index|

  puts "#{index + 1}: #{book[:title]}"

end

 
 

参考にさせていただいたサイト

2
0
5

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