In Ruby, I am trying to display items that are in an array of arrays if both items in the array are present. For example: [["ABC Inc", "This is a test"], ["XYZ Inc", "This is a second test"], ["EFG Inc", ""]]
When displaying this array on the front end, I would like to display the first set and second set, but not display the third: EFG Inc, as it is missing the second item in the array.
The front end currently displays:
ABC Inc: This is a test
XYZ Inc: This is a second test
EFG Inc:
CodePudding user response:
In Ruby I would use Array#select
to only pick those nested arrays that have all elements being present, like this:
nested_array = [["ABC Inc", "This is a test"], ["XYZ Inc", "This is a second test"], ["EFG Inc", ""]]
nested_array.select { |array| array.none?(&:empty?) }
#=> [["ABC Inc", "This is a test"], ["XYZ Inc", "This is a second test"]]
See Array#none?
and String#empty?
In Ruby on Rails, you can also use Array#all?
and Object#present?
which reads nicer and also covers nil
elements:
nested_array = [["ABC Inc", "This is a test"], ["XYZ Inc", "This is a second test"], ["EFG Inc", ""]]
nested_array.select { |array| array.all?(&:present?) }
#=> [["ABC Inc", "This is a test"], ["XYZ Inc", "This is a second test"]]