LoginSignup
2
2

More than 3 years have passed since last update.

【Ruby】Ruby初心者がよく使うと思う配列のメソッド

Posted at

はじめに

いま、Rubyプログラマに勧めてもらったチェリー本を使って学習を進めています。
Rubyの勉強を開始してから1週間くらいしか経っていない初心者が、覚えておきたい配列のメソッドを調べました。
個人的な振り返りメモも兼ねています。
ぜひ間違えていたら、コメントや編集リクエストで教えていただけると嬉しいです。

参考文献

プロを目指す人のためのRuby入門 言語仕様からテスト駆動開発・デバッグ技法まで Software Design plus | 伊藤 淳一 | コンピュータ・IT | Kindleストア | Amazon
start_with? (String) - Rubyリファレンス
class Array (Ruby 2.6.0)
Rubyのeachでindexを取得する:each_with_index | UX MILK
【Ruby】each_with_indexは知ってたけどeach.with_indexは知らなかった… - 訳も知らないで
class Enumerator (Ruby 2.6.0)

動作確認環境

  • Windows 10
  • ruby 2.5.5p157

eachメソッドでループする

今回勉強に使わせてもらっているチェリー本によると、for文ではなく、eachメソッドを使用することが多いとのことです。

arr = ['Spring', 'Summer', 'Autumn', 'Winter']
arr.each do |n|
  puts n
end

実行結果

Spring
Summer
Autumn
Winter

eachメソッドでindex(添字)を取得したい

Enumerableモジュールのメソッドの一つであるeach_with_indexを使用します。

arr = ['Spring', 'Summer', 'Autumn', 'Winter']
arr.each_with_index do |n, index|
  puts "#{index}, #{n}"
end

実行結果

0, Spring
1, Summer
2, Autumn
3, Winter

index(添字)の始まりの値を設定したい

Enumeratorクラスのメソッドの一つであるwith_indexメソッドを使用します。
サンプルは、2からindexを開始するという意味です。

arr = ['Spring', 'Summer', 'Autumn', 'Winter']
arr.each.with_index(2) do |n, index|
  puts "#{index}, #{n}"
end

実行結果

2, Spring
3, Summer
4, Autumn
5, Winter

配列同士を比較したい

サンプルコード

arr = ['Spring', 'Summer', 'Autumn', 'Winter']
arr_compare = ['Spring', 'Summer', 'Autumn']
puts arr.eql?arr_compare   # false
arr_compare.push('Winter') # 要素を追加してから比較
puts arr.eql?arr_compare   # true

配列が空かどうか確認

arr = ['Spring', 'Summer', 'Autumn', 'Winter']
arr_empty = []
puts arr_empty.empty? # true
puts arr.empty?       # false

指定した範囲の配列要素を取得する

サンプルコード

arr = ['Spring', 'Summer', 'Autumn', 'Winter']
p arr[1...3] # 3を含まない
p arr[1..3]  # 3を含む

実行結果

["Summer", "Autumn"]
["Summer", "Autumn", "Winter"]

条件に一致する要素を取り出して新しい配列を作る

サンプルコード

arr = ['Spring', 'Summer', 'Autumn', 'Winter']
# 文字列の先頭がSの要素を抽出
p arr.select { |n| n.start_with?("S") }

実行結果

["Spring", "Summer"]

条件と不一致の要素を取り出して新しい配列を作る

サンプルコード

arr = ['Spring', 'Summer', 'Autumn', 'Winter']
# 文字列の最後尾がrの要素を抽出
p arr.reject { |n| n.end_with?("r") }

実行結果

["Spring", "Autumn"]

全要素に対してブロック内で評価した結果で新しい配列を作る

p arr.map { |n| n.start_with?("S") }

実行結果

[true, true, false, false]

条件に一致する最初の要素を返す

サンプルコード


# uを含む文字列を検索
p arr.find { |n| n.index("u")}

実行結果

"Summer"

おわりに(おまけ)

実はチェリー本を購入する前に、
この記事の下書きを作っていたのですが、
だいたい(もしかしたら全部)チェリー本に書いていました。

まとめた意味がなくなってしまい、すごく悲しくなりました。

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