LoginSignup
7
0

More than 5 years have passed since last update.

Rubyで配列を番号と一緒に展開したい時はeach.with_indexが便利

Last updated at Posted at 2018-06-08

前提

items = ['Apple', 'Pen', 'Pineapple']

といった配列があったとき

1 番は Apple
2 番は Pen
3 番は Pineapple

と表示させたい!どうしよう・・・

やり方

①変数を定義しeachで配列を展開しながら最後にインクリメントする

i = 1
items.each do |item|
  puts "#{i} 番は #{item}"
  i += 1
end

JSだとmapと一緒に展開できるのにな〜と思いながらこう書いてました

②変数と一緒に配列をeach_with_indexで展開する

items.each_with_index do |item, i|
  puts "#{i+1} 番は #{item}"
end

しかし、こんなものがあると知った!
でも、最初のiは0なので0番目からになってしまう・・
+1する必要がある・・

③変数と一緒に配列をeach.with_indexで展開する

items.each.with_index(1) do |item, i|
  puts "#{i} 番は #{item}"
end

でもeach.with_indexをつかって1を渡してあげればi+1とかかずにスッキリ書けました
便利!!これから使おうっと

感想

最近Rubyを触る機会が多いのですがめちゃくちゃ便利なメソッドがある、そして数が多い・・・
力技で解決せずに冗長だなと思ったら探して良い書き方を模索してノウハウを蓄積していきたいです!

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