はじめに
rubyのarrayに対するメソッドで、普段あまり使わないメソッドをまとめてみました。
bsearch
条件を満たす値を一つ返す
ary = [1,2,3,4]
ary.bsearch { |n| n > 1 }
# => 2
combination
引数nのサイズの組み合わせを作成する
ary = [1,2,3,4,5]
ary.combination(2).to_a
# => [[1, 2], [1, 3], [1, 4], [1, 5], [2, 3], [2, 4], [2, 5], [3, 4], [3, 5], [4, 5]]
compact
nilを削除する
ary = [1,2,nil,4,5,nil]
ary.compact
# => [1, 2, 4, 5]
cycle
配列の全ての要素に対して、引数のn回処理を行う
ary = [1,2]
ary.cycle(2) { |x| p x }
1
2
1
2
# => nil
difference
引数に渡した要素を配列から取り除く
ary = [1,2,3,4,5,6]
ary.difference([2,4])
# => [1, 3, 5, 6]
dig
ネストした要素の値を参照
ary = ['a',[['b','c'],['d','e']]]
ary.dig(1,1,0)
# => "d"
drop(n)
先頭のn個の要素を削除
ary = [1,2,3,4,5,6,7]
ary.drop(3)
# => [4, 5, 6, 7]
drop_while
ブロック内がfalseを返す要素の手間までを削除
ary = [1,2,3,4,5,6,7]
ary.drop_while { |x| x < 3 }
# => [3, 4, 5, 6, 7]
fill
要素を全て引数の値に置き換える
ary = [1,2,3,4,5,6,7]
ary.fill(nil)
# => [nil, nil, nil, nil, nil, nil, nil]
filter
ブロック内でtrueを返すもののみを残す
ary = [1,2,3,4,5,6,7,8]
ary.filter(&:even?)
=> [2, 4, 6, 8]
one?
trueを返すものが一つのみの場合にtrueを返す
ary = [1,2,3,4,5,6]
ary.one? { |x| x.even? }
# => false
ary.one? { |x| x > 5 }
# => true
permutation(n)
nサイズの順列を作成
ary = [1,2,3,4,5,6]
ary.permutation(2).to_a
# => [[1, 2], [1, 3], [1, 4], [1, 5], [1, 6], [2, 1], [2, 3], [2, 4], [2, 5], [2, 6], [3, 1], [3, 2], [3, 4], [3, 5], [3, 6], [4, 1], [4, 2], [4, 3], [4, 5], [4, 6], [5, 1], [5, 2], [5, 3], [5, 4], [5, 6], [6, 1], [6, 2], [6, 3], [6, 4], [6, 5]]
product
配列と引数の配列の要素をそれぞれ合わせた配列を作成する
ary = [1,2,3,4,5]
ary.product(['a', 'b'])
# => [[1, "a"], [1, "b"], [2, "a"], [2, "b"], [3, "a"], [3, "b"], [4, "a"], [4, "b"], [5, "a"], [5, "b"]]
rotate
配列の最初の要素を最後に持ってくる
ary = [1,2,3,4,5]
ary.rotate
# => [2, 3, 4, 5, 1]
sample
ランダムに値を取ってくる
ary = [1,2,3,4,5]
ary.sample
# => 3
transpose
行と列を入れ替える
ary = [[1,2],[3,4],[5,6]]
ary.transpose
# => [[1, 3, 5], [2, 4, 6]]