Is there a way to split an array of objects in Rails by two different delimiters?
ruby, ruby-on-rails-4
Solution
You're looking for the standard method `Enumerable#partition`, rather than the Rails `split` add-on.
@residenciais, @comerciais = TipoImovel.all.partition { |t| t.residencial? }
Which can also be written like this, since the condition is a single method call:
@residenciais, @comerciais = TipoImovel.all.partition(&:residencial?)
Some more explanation:
The Rails `Array#split` method is used to separate an array into ordered groups delimited by elements which return true for a given block. It's a generalization of the standard String method. For example:
[1,2,3,4,5,6].split(&:odd?) #=> [[], [2], [4], [6]]
Any odd number is a delimiter, so it returns the portions of the array between the odd numbers, in order.
Whereas this is closer to what you're doing:
odds, evens = [1,2,3,4,5,6].partition(&:odd?) #=> [[1, 3, 5], [2, 4, 6]]
If the partition condition is not simply Boolean, or if you want to key off the values regardless, then you can use `Enumerable#group_by`, which returns a Hash of Arrays instead of a pair:
[1,2,3,4,5,6].group_by(&:odd?) #=> {true=>[1, 3, 5], false=>[2, 4, 6]}
Problem
I would like to do something like this: ``` @residenciais, @comerciais = TipoImovel.all.split { |t| t.residencial? } ``` The problem is that `@comerciais` is always empty because it never returns the object, since the condition is false. Is there a better way of doing this?