[Ruby] Ruby array operations

less than 1 minute read

map

Image that returns an array of group ids with 5 or more people


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

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

Elements that do not meet the condition will be nil

#.reject(&:blank?) Remove nil and empty string from array


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 the concatenated string. You can insert the character string put in the argument

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

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

Tags: ,

Updated: