1
0

Rubyの基本(配列 Part1)

Last updated at Posted at 2024-02-29

配列の作成

順序が重要なデータは配列で管理する。
「puts」ならば値を順番に表示、「p」ならばリテラル表現で表示される。
「length」や「size」で格納されている値の個数を調べることができる。

sample_01.rb
scores = [70, 90, 80]

# 値を順番に表示(改行付き)
puts scores
=begin
70
90
80
=end

# リテラル表現
p scores # [70, 90, 80]

# length も size も使用可能
p scores.length # 3
p scores.size # 3

配列の操作

配列に対しては、値の挿入、配列同士の連結、値の削除ができる。

sample_02.rb
# 値の挿入
scores = [70, 90, 80]
scores << 85
p scores # [70, 90, 80, 85]

# 配列同士の連結
more_scores = [40, 50]
scores += more_scores
p scores # [70, 90, 80, 85, 40, 50]

# 値の特定の位置への挿入
scores.insert(1, 75)
p scores # [70, 75, 90, 80, 85, 40, 50]

# 値の削除
scores.delete_at(0)
p scores # [75, 90, 80, 85, 40, 50]

配列について調べる

配列について調べるためのメソッドとして、以下のものがある。
「true」か「false」を返すメソッドには慣習上「?」を付ける。

sample_03.rb
scores = [70, 90, 80]

# 中身が空かどうか
p scores.empty? # false

# 特定の値が含まれているかどうか
p scores.include?(90) # true

# 特定の値のインデックス番号(値が存在しない場合はnilを返す)
p scores.index(80) # 2
p scores.index(40) # nil

配列の並び替え

配列の値を並び替えるメソッドとして、以下のものがある。
元のデータを直接更新する場合は、慣習上メソッド名に「!」を付ける。

sample_04.rb
scores_01 = [70, 90, 80]

# 昇順に並び替え
sorted_scores = scores_01.sort
p sorted_scores # [70, 80, 90]

# 元の配列を直接更新して昇順に並び替え
scores_02 = [300, 200, 100]
p scores_02.sort! # [100, 200, 300]

# 元の配列を逆順に並び替え
scores_03 = [600, 400, 500]
p scores_03.reverse! # [500, 400, 600]

# 値をランダムな順番に並び替え
scores_04 = [700, 800, 900]
p scores_04.shuffle! # [900, 700, 800]

文字列を値に持つ配列

文字列を値に持つ配列の定義方法、操作方法は以下

sample_05.rb
# 配列の定義
names_01 = ["Taro", "Jiro", "Saburo"]
p names_01 # ["Taro", "Jiro", "Saburo"]

# 別の書き方
names_02 = %W(Taro Jiro Saburo)
p names_02 # ["Taro", "Jiro", "Saburo"]

# 値の連結
connected_names = names_01.join
p connected_names # "TaroJiroSaburo"

# 値の連結(区切り文字を指定)
connected_names = names_01.join(", ")
p connected_names # "Taro, Jiro, Saburo"

each文による値の表示

each文ではインデックス番号を表示することもできる。

sample_06.rb
scores = [70, 90, 80]

scores.each_with_index do |score, index|
  puts "Score #{index}: #{score}"
end
=begin
Score 0: 70
Score 1: 90
Score 2: 80
=end
1
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
1
0