Ruby array manipulation

map Image that returns the id of a group with 5 or more people as an array


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

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

Elements that do not meet the conditions will be nil

.reject(&:blank?) Eliminate nil and empty strings from arrays


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

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

filter_map Summarize the above. Available from Ruby 2.7


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

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

join Returns a concatenated string. You can insert the character string in the argument

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

['A','B','C'].join('|')
#=> "A|B|C"

Recommended Posts

Ruby array manipulation
JavaScript array manipulation
Hanachan in Ruby (non-destructive array manipulation)
Ruby two-dimensional array
[Ruby] Extracting a two-dimensional array
Array
Three Bit Manipulation Methods (Ruby)
[Ruby] Get array elements alternately.
Array
Sorting hashes in a Ruby array
[Ruby] Extracting double hash in array
Explanation about Array object of Ruby
What is a Ruby 2D array?
Ruby learning 4
Java array
Array practice
Ruby basics
Ruby learning 5
Java array
Ruby basics
java (array)
Ruby Review 2
Ruby addition
Refactoring Ruby
Java array
[Java] Array
Ruby learning 3
Array practice 2
Ruby setting 2
Java array
Ruby problem ⑦
[Ruby] Get unique elements from an array
[Ruby] Block
Refactoring Ruby
ruby calculator
Ruby learning 6
12 of Array
Ruby settings 1
Refactoring Ruby
java array
Sort an array of Ruby homebrew classes
[Java] Array
Ruby basics
Ruby memo
Ruby learning 1
Ruby Review 1
[Ruby] Module
[Ruby] Calculation by extracting elements from an array