配列の生成
a = [1, 2, 3]
=> [1, 2, 3]
a.class
=> Array
Array[1, 2, 3]
=> [1, 2, 3]
Array.new(3, "str")
=> ["str", "str", "str"]
Array.new([1, 2, 3])
=> [1, 2, 3]
Array.new(5) {|i| i * 3}
=> [0, 3, 6, 9, 12]
配列に要素追加
a = [1, 2, 3]
=> [1, 2, 3]
<<メソッド
a << 4
=> [1, 2, 3, 4]
concatメソッド(破)
a.concat[5, 6]
=> [1, 2, 3, 4, 5, 6]
insertメソッド
a.insert(3, 9)
=> [1, 2, 3, 9, 4, 5, 6]
a.object_id
=> 47409483356240
b = a + [10]
=> [1, 2, 3, 9, 4, 5, 6, 10]
b.object_id
=> 47409481926320
unshiftメソッド
b.unshift(10) (破)
=> [10, 1, 2, 3, 9, 4, 5, 6, 10]
配列の要素変更
[]=メソッド
a = [1, 2, 3]
=> [1, 2, 3]
a[1] = 10
=> 10
a
=> [1, 10, 3]
a[1..2] = [10, 11]
=> [10, 11]
a
=> [1, 10, 11]
a[8] = 5
=> 5
a
=> [1, 10, 11, nil, nil, nil, nil, nil, 5]
fillメソッド
a = [1, 2, 3]
=> [1, 2, 3]
a.fill("s")
=> ["s", "s", "s"]
a.fill("t", 1..2)
=> ["s", "t", "t"]
a
=> ["s", "t", "t"]
a.fill(1..2){|index| index}
=> ["s", 1, 2]
replaceメソッド
a = [1, 2, 3]
=> [1, 2, 3]
a.object_id
=> 47409483213220
a.replace([4, 5, 6])
=> [4, 5, 6]
a.object_id
=> 47409483213220
配列の要素参照
a = [1, 2, 3]
=> [1, 2, 3]
[]メソッド
a[1]
=> 2
a[1..2]
=>[2, 3]
atメソッド
a.at(1)
=> 2
# 要素 < indexの場合、nilが返る
values_atメソッド
a.values_at(1)
=> [2]
fetchメソッド
a.fetch(4)
IndexError: index 4 outside of array bounds: -3...3
a.fetch 4, "ERROR"
=> "ERROR"
a.fetch(4){|n| "ERROR #{n}"}
=> "ERROR 4"
firstメソッド
a.first
=> 1
a.first(2)
=> [1, 2]
lastメソッド
a.last
=> 3
assocメソッド
a.assoc(3)
=> [3, 4]
# 配列の配列を検索。最初の要素が指定された値と==で、その配列を返す。
rassocメソッド
a.rassoc(4)
=> [3, 4]
# index1の要素を検索。
配列の要素調べ
a = [1, 2, 3, 4, 5]
=> [1, 2, 3, 4, 5]
include?メソッド
a.include?(3)
=> true
a.include?(6)
=> false
indexメソッド
a.index(4)
=> 3
a.rindex(4)
=> 3
# 該当しない場合、nilを返す。
配列の要素削除
a = [1, 2, 3, 4, 5]
=> [1, 2, 3, 4, 5]
delete_atメソッド
a.delete_at(2)
=> 3
a
=> [1, 2, 4, 5]
delete_ifメソッド
a = [1, 2, 3, 4, 5]
=> [1, 2, 3, 4, 5]
a.delete_if{|n| n % 2 == 0}
=> [1, 3, 5]
deleteメソッド
a = [1, 2, 3, 4, 5]
=> [1, 2, 3, 4, 5]
a.delete(3)
=> 3
a = [1, 2, 4, 5]
a.delete(10)
=> nil
a = [1, 2, 4, 5]
clearメソッド
a = [1, 2, 3, 4, 5]
=> [1, 2, 3, 4, 5]
a.clear
=> []
slice!メソッド
a = [1, 2, 3, 4, 5]
=> [1, 2, 3, 4, 5]
a.slice!(2, 2)
=> [3, 4]
a
=> [1, 2, 5]
shiftメソッド
a = [1, 2, 3, 4, 5]
=> [1, 2, 3, 4, 5]
a.shift(2)
=> [1, 2]
a.shift
=> 3
a
=> [4, 5]
# 先頭から指定された数だけ要素を取り除いて返す。指定がなければ1。
popメソッド
a = [1, 2, 3, 4, 5]
=> [1, 2, 3, 4, 5]
a.pop(2)
=> [4, 5]
a.pop
=> 3
a
=> [1, 2]
- メソッド
a = [1, 2, 3, 4, 5]
=> [1, 2, 3, 4, 5]
a - [1, 2]
=> [3, 4, 5]
a - [1, 3, 5, 7]
=> [2, 4]
配列の演算
| メソッド
[1, 2, 3] | [1, 3, 5]
=> [1, 2, 3, 5]
# 和集合
& メソッド
[1, 2, 3] & [1, 3, 5]
=> [1, 3]
# 積集合
配列の比較
== メソッド
[1, 2, 3] == [1, 3, 5]
=> false
[1, 2, 3] <=> [1, 3, 5]
=> -1
# 左辺が大きければ、0。右辺が大きければ-1。同じ0。