0
0

More than 3 years have passed since last update.

Posted at

# はじめに

rubyのarrayに対するメソッドで、普段あまり使わないメソッドをまとめてみました。

# bsearch

``````ary = [1,2,3,4]
ary.bsearch { |n| n > 1 }
# => 2
``````

# combination

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

``````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)

``````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]]
``````
0
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
0
0