Rubyの配列に関する便利な文法

  • 3
    Like
  • 1
    Comment

push:配列を合体する

例1:

array = [1, 2, 3]
array.push(10, 100)
p array
[1, 2, 3, 10, 100]

例2:

arr_1 = [0, 1, 2]
=> [0, 1, 2]

arr_2 = [8, 9, 10]
=> [8, 9, 10]

arr_1.push(arr_2))
=> [0, 1, 2, [8, 9, 10]]

pushは「<<」と同義

a = [1, 2]
=> [1, 2]

b = [3, 4]
=> [3, 4]

a << b
=> [1, 2, [3, 4]]

どちらも重複した配列になる。

concat:配列を合体する

arr_1 = [0, 1, 2]
=> [0, 1, 2]

arr_2 = [8, 9, 10]
=> [8, 9, 10]

 arr_1.concat(arr_2)
=> [1, 2, 3, 8, 9, 10]

+演算子と同義。

a = [1, 2]
=> [1, 2]

b = [3, 4]
=> [3, 4]

a + b
=> [1, 2, 3, 4]

重複しない。

flatten! :重複配列をフラットにする

(flattenでも可)
「!」は破壊的メソッドなので使用しないほうがいいかも。

arr_1 = [0, 1, 2]
=> [0, 1, 2]

arr_2 = [8, 9, 10]
=> [8, 9, 10]

arr_1.push(arr_2))
=> [0, 1, 2, [8, 9, 10]]
# 重複しても、、、

arr_1.flatten!
=> [0, 1, 2, 8, 9, 10]
# 解決!

配列の要素を数指定で取得

arr = [0,1,2,3,4,5,6,7,8,9,10]
=> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# 「.」が2つのとき、10個の要素
arr[0..9]
=> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

# 「.」が2つのとき、10個の要素
arr[1..9]
=> [1, 2, 3, 4, 5, 6, 7, 8, 9]

# 「.」が3つのとき、9個の要素
arr[0...9]
=> [0, 1, 2, 3, 4, 5, 6, 7, 8]

# [0..9]の中からランダムに2つだけ取る
arr[0..9].sample(2)
=> [4, 2]

sample:要素をランダムに取得する

arr = [0,1,2,3,4,5,6,7,8,9,10]
=> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

arr.sample(4)
=> [0, 8, 1, 4]

shuffle:シャッフルする

arr = [0,1,2,3,4,5,6,7,8,9,10]
=> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

arr.shuffle
=> [4, 8, 9, 2, 5, 1, 3, 7, 10, 0, 6]

arr.shuffle!
=> [5, 0, 4, 7, 6, 2, 1, 9, 10, 3, 8]

uniq:重複した要素を取り除く

a = [0, 1, 2, 4, 6, 3]
=> [0, 1, 2, 4, 6, 3]

b = [0, 1, 2, 6, 3, 5]
=> [0, 1, 2, 6, 3, 5]

c = ((a.sample(3)) + (b.sample(3)))
=> [6, 2, 1, 2, 5, 6]

# ユニークにする
c = ((a.sample(3)) + (b.sample(3))).shuffle!.uniq
=> [0, 6, 2, 3]

c = ((a.sample(3).uniq) + (b.sample(3)).uniq).shuffle!
=> [3, 1, 1, 2, 0, 4]

c = ((a.sample(3)) + (b.sample(3))).uniq.shuffle!
=> [4, 2, 3, 1, 6]

c = ((a.sample(3)) + (b.sample(3))).uniq.shuffle!
=> [0, 6, 4, 3, 1, 2]

combination:組み合わせ

arr = [1, 2, 3]
=> [1, 2, 3]

arr.combination(2){|x| print x}
[1, 2][1, 3][2, 3]=> [1, 2, 3]

3個の要素から2個を選んだ。
3C2の計算 = 3P2/2! = 3通り

permutation:順列

arr = [1, 2, 3]
=> [1, 2, 3]

arr.permutation(2){|x| print x}
[1, 2][1, 3][2, 1][2, 3][3, 1][3, 2]=> [1, 2, 3]

3P2 = 6通り