LoginSignup
1
0

More than 3 years have passed since last update.

Rubyのメソッド(配列編)

Posted at

はじめに

Ruby APIを読んでいて、Rubyにそんなメソッドあるの!?と面白くなったメソッドを書いていきます。
バージョンは2.7です。

色々なメソッドがあって勉強になりました。

compact、compact!

配列の中のnilを取り除いてくれます。
nilだけを狙い撃ちしてくれるだなんてRubyさん優秀ですね(使い所はピンと来ていない)

arr = ['foo', 0, nil, 'bar', 7, 'baz', nil]
arr.compact  #=> ['foo', 0, 'bar', 7, 'baz']
arr          #=> ['foo', 0, nil, 'bar', 7, 'baz', nil]
arr.compact! #=> ['foo', 0, 'bar', 7, 'baz']
arr          #=> ['foo', 0, 'bar', 7, 'baz']

delete_if、keep_if

配列から条件に合うものを削除したり、残したりした後の配列を作ってくれます。
簡単な条件ならこんなに短く書けるんですね。
後置if文よりスッキリしているのでは

arr.delete_if {|a| a < 4}   #=> [4, 5, 6]
arr                         #=> [4, 5, 6]

arr = [1, 2, 3, 4, 5, 6]
arr.keep_if {|a| a < 4}   #=> [1, 2, 3]
arr

array *

配列には掛け算が使えるのですが、掛けるものがint型かString型かで結果が変わります。
数値を掛けると、元の配列をその回数分繰り返した配列を返します。
そして、文字列を掛けると、掛けたもので区切った文字列を返します。
つまり、Array#join(str)と同じ結果です。

[ 1, 2, 3 ] * 3    #=> [ 1, 2, 3, 1, 2, 3, 1, 2, 3 ]
[ 1, 2, 3 ] * ","  #=> "1,2,3"

combination

その配列の中で、引数と同じ長さの配列をすべて作って返してくれます。
a.combination(2).to_aでは、1と2、1と3、・・・3と4というように数字が2つの配列を作って返しています。

a = [1, 2, 3, 4]
a.combination(1).to_a  #=> [[1],[2],[3],[4]]
a.combination(2).to_a  #=> [[1,2],[1,3],[1,4],[2,3],[2,4],[3,4]]
a.combination(3).to_a  #=> [[1,2,3],[1,2,4],[1,3,4],[2,3,4]]
a.combination(4).to_a  #=> [[1,2,3,4]]
a.combination(0).to_a  #=> [[]] # one combination of length 0
a.combination(5).to_a  #=> []   # no combinations of length 5

dig

引数の数だけ配列の中に潜って値を取ってきてくれます。
つまり、a[0][1][1]ということですね。
digを使ったほうが何を示すかわかりやすい気がするんですけどどうなんでしょう?

a = [[1, [2, 3]]]

a.dig(0, 1, 1)                    #=> 3
a.dig(1, 2, 3)                    #=> nil

transpose

配列の行列を入れ替えた配列を返してくれます。
これ、メソッド使わないでやると力不足で難しいので、便利だと思います。

a = [[1,2], [3,4], [5,6]]
a.transpose   #=> [[1, 3, 5], [2, 4, 6]]
1
0
1

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
1
0