3
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

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

Last updated at Posted at 2018-01-26

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

参考
パーフェクトRuby
https://docs.ruby-lang.org/ja/latest/class/Array.html

要素の取得

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
深い階層にある値を引っこ抜く。keyが見つからない場合はnilが返る。
ネストした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
配列の要素からnilを取り除く

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"
3
5
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
3
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?