5

More than 5 years have passed since last update.

# [Ruby]Arrayクラスのメソッド

Last updated at Posted at 2018-01-26

1年くらい前にRubyの勉強のためにArrayクラスの便利メソッドをまとめたもの

## 要素の取得

values_at

``````ary = [3, 4, 2, 8]
ary.values_at(0, 3, 4) # => [3, 8, nil]
``````

sample
selfからランダムに要素を返す

``````ary = [3, 4, 2, 8]
ary.sample # => 2

# 引数を設定すると返す要素の個数を指定できる
array.sample(2) => [4, 2]
``````

assoc

``````ary = [[:ruby, 5], [:java, 3], [:c, 1]]
ary.assoc(:ruby) # => [:ruby, 5]
``````

dig

ネストしたHashや配列へのアクセスがしやすくなる。

``````# Hash
h = { foo: {bar: {baz: 1}}}
h.dig(:foo, :bar, :baz) # => 1
h.dig(:hoge)            # => nil

g = { foo: [10, 11, 12] }
g.dig(:foo, 1)          # => 11

# Array
a = [[4, [5, 6]]]

a.dig(0,1,0) # => 5
a.dig(0,1,1) # => 6
a.dig(0,1)   # => [5, 6]
a.dig(1)     # => nil
a.dig(0,0,0) # => TypeError: Integer does not have #dig method
``````

## 配列の整形

compact

``````array = [false, nil, 0, '', [0, nil], []]
array.compact # => [false, 0, "", [0, nil], []]
``````

uniq

``````array = ['ruby', 'ruby', 2, 2.0, 2]
array.uniq # => ["ruby", 2, 2.0]
``````

flatten

``````array = [1, 2, [3, 4], 5]
array.flatten # => [1, 2, 3, 4, 5]
``````

transpose

``````array = [[1, 2, 3], ['北海道', '青森', '秋田']]
array.transpose # => [[1, "北海道"], [2, "青森"], [3, "秋田"]]
``````

## 二分探索

bsearch

``````array = [1, 2, 3, 5, 8]

array.bsearch { |n| n > 4 } # => 5
array.bsearch { |n| n > 9 } # => nil
``````

## 要素の連結

join

``````array = [1, 2, [3, 4], 5]
array.join # => "12345"
# セパレータとなる文字列を引数に指定も可能
array.join(',') # => "1,2,3,4,5"

# Array#*メソッドでも同じことが可能だけど暗号っぽくなるので非推奨(StyleGuideより）
array.*(',') # => "1,2,3,4,5"
``````

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
5