11
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Ruby eachメソッド(配列)

Last updated at Posted at 2018-07-29

eachメソッド

Rubyにはeachというメソッドがあります。
配列範囲オブジェクトなどで用意されているメソッドで、for文に似た動作をします。

eachメソッドは、ブロック変数(ブロックパラメータ)に配列の要素を代入しながら、
配列・範囲オブジェクトの要素数を繰り返します。

オブジェクト.each do |変数|
繰り返す処理
end

範囲オブジェクトの場合

(1..10).each do |num|
print("num = ", num,"\n")
end

//実行結果
num = 1
num = 2
num = 3
num = 4
num = 5
num = 6
num = 7
num = 8
num = 9
num = 10

配列の場合

fruits = ["orange", "banana", "apple"]

fruits.each do |fruit|
 puts fruit,"\n"
end

//実行結果
orange
banana
apple

*「"\n"」は改行の意味

11
6
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
11
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?