LoginSignup
0
0

More than 3 years have passed since last update.

Rubyの配列操作

Last updated at Posted at 2020-06-21

map

人数が5人以上のgroupのidを配列で返すイメージ


ids = groups.map{ |group| group.id if group.count >= 5}

#=> [1, 2, nil, 4, ・・・]

条件に当てはまらない要素はnilになる

.reject(&:blank?)

配列からnilと空文字を無くす


ids = groups.map{ |group| group.id if group.count >= 5}.reject(&:blank?)

#=> [1, 2, 4, ・・・]

filter_map

上記をまとめて。Ruby2.7から利用可能


ids = groups.filter_map{ |group| group.id if group.count >= 5}

#=> [1, 2, 4, ・・・]

join

連結した文字列を返す。引数に入れた文字列を挟み込みことができる

['A','B','C'].join
#=> "ABC"

['A','B','C'].join('|')
#=> "A|B|C"
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