LoginSignup
0
0

More than 1 year has passed since last update.

[ruby] each_with_index, each.index_with, each_indexの違い

Last updated at Posted at 2022-06-28

はじめに

paizaで出てきたメソッドの違いをまとめました

参考にさせていただきました!

結論

.each_with_index
  通常のeach + 0からカウントするindexを得る
.each.with_index
  動きは上と同じ
.each_index
  要素分+1 indexを得る

each_with_indexとeach.with_indexの違い

each_with_indexはindexが0からスタートする
each.with_index(1)と引数を渡すと(0ではなく)1番目から始められるためi+1とやる必要がなくなる

使い方

array = ["a", "b"]

array.each_with_index do |a, i|
  puts "「#{i} #{a}」"
end
#=> 結果
#   「0 a」 
#   「1 b」 

array.each.with_index(20) do |a, i|
  puts "「#{i} #{a}」"
end
#=> 「20 a」
#   「21 b」 

array.each_index do |i|
  puts "「#{i}」"
end
#=>  「0」
#      「1」 

ちなみに

リファレンスによるとeach_with_indexにも引数を渡せて、splitのような動きをしてくれる?っぽいです

require 'stringio'
StringIO.new("foo|bar|baz").each_with_index("|") do |s, i|
  p [s, i]
end
# => ["foo|", 0]
#    ["bar|", 1]
#    ["baz", 2]

最後に

間違いがあればお知らせいただけると幸いです
閲覧ありがとうございました!

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