1
1

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: 配列からすべての要素を番号つきで取り出す (3パターン)

Last updated at Posted at 2018-08-26

配列オブジェクトpostsのすべての要素を番号つきで取り出したいときの、3パターンの書き方です。

1. eachメソッド

・シンプルな書き方

.rb
posts = ["こんにちは", "たのしい", "さようなら"]

number = 0
posts.each do |text|
  puts "#{number}番目の投稿:#{text}"
  number += 1
end

# 結果
0番目の投稿こんにちは
1番目の投稿たのしい
2番目の投稿さようなら

# 番号を1からスタートさせたい場合は、

number = 1
posts.each do |text|
  puts "#{number}番目の投稿:#{text}"
  number += 1
end

# 結果
1番目の投稿こんにちは
2番目の投稿たのしい
3番目の投稿さようなら

2. each_with_indexメソッド

・eachメソッドよりソースコードが少なくて済む
・番号は0から開始する

.rb
posts = ["こんにちは", "たのしい", "さようなら"]

posts.each_with_index do |text, i|
  puts "#{i}番目の投稿:#{text}"
end

# 結果
0番目の投稿こんにちは
1番目の投稿たのしい
2番目の投稿さようなら

# 番号を1からスタートさせたい場合は、

posts.each_with_index do |text, i|
  puts "#{i+1}番目の投稿:#{text}"
end

# 結果
1番目の投稿こんにちは
2番目の投稿たのしい
3番目の投稿さようなら
```

## 3. each.with_indexメソッド

・開始したい番号を簡単に指定できる

``````.rb
posts = ["こんにちは", "たのしい", "さようなら"]

posts.each.with_index(5) do |text, i|
  puts "#{i}番目の投稿:#{text}"
end

# 結果
5番目の投稿:こんにちは
6番目の投稿:たのしい
7番目の投稿:さようなら
```



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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?