【Ruby】for文の使い方

for文は、変数にオブジェクトの中身を1つずつ代入し終わるまで処理します。

for 変数 in オブジェクト do
  繰り返しの処理
end


変数に格納されたデータを1つ1つオブジェクトに渡しながらdo endの中に書かれた処理が実行されます。


文字列の配列

strs = ['a', 'b', 'c']
for strs in str do
  puts str
end

a
b
c


数値の配列

strs = [1, 2, 3]
for str in strs do
  puts str
end

1
2
3


配列の配列

strs = [['a',1], ['b',2], ['c',3]]
for str in strs do
  puts str
end

a
1
b
2
c
3


ハッシュの配列

strs = {dog: '', cat: ''}
for str in strs do
  puts str
end

dog
犬
cat
猫