Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationEventAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
5
Help us understand the problem. What are the problem?

More than 3 years have passed since last update.

posted at

updated at

Organization

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

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"
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
5
Help us understand the problem. What are the problem?