Code to loop through an array in one line in Ruby

Viewed 157

I am looping through the array self.sisters as below:

brothers_in_law = []
self.sisters&.each do |sister|
  brothers_in_law << sister.spouse (if !sister.spouse.nil?)
end

How can I write it in the ruby way and also in one line?

2 Answers

In ruby, a rule of thumb is: if you have an each loop that is used for anything other than simply iterating the elements, there is 99% chance there is a better method.

brothers_in_law = sisters.map(&:spouse).reject(&:nil?)
# or 
brothers_in_law = sisters.map(&:spouse).compact
# or in ruby 2.7+
brothers_in_law = sisters.filter_map(&:spouse)

Testing:

sister = OpenStruct.new(spouse: "1")
sister1 = OpenStruct.new(spouse: "2")
sister2 = OpenStruct.new(spouse: nil)
sisters = [sister, sister1, sister2, nil]
brothers_in_law = []
brothers_in_law.concat sisters.compact&.map(&:spouse).compact unless sisters.nil?
=> ["1", "2"]

The compact calls remove the nil values on both sisters and their spouses, so only the spouse objects that exist are returned.

Related