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

eachおよびeachの派生系の使い方。

Posted at

each

fruits = ["メロン", "ブドウ", "リンゴ"]
fruits.each do |fruit|
  puts fruit
end
# 出力:
# メロン
# ブドウ
# リンゴ

コレクションから値を一つずつ取り出す動作をする

each_slice


numbers = (1..7)
numbers.each_slice(3) do |slice|
  p slice
end
# 出力:
# [1, 2, 3]
# [4, 5, 6]
# [7]

コレクションからn個ずつ値を取り出す

each_with_index


fruits = ["メロン", "ブドウ", "リンゴ"]
fruits.each_with_index do |fruit, index|
  puts "インデックス#{index}: #{fruit}"
end
# 出力:
# インデックス0: メロン
# インデックス1: ブドウ
# インデックス2: リンゴ

eachの機能に加えて、番号もついたバージョン

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?