Partition array using index in ruby
ruby
Solution
You can do:
["a","b",3,"c",5].partition.with_index { |_, index| index <= 2 }
Following @toro2k advice, I think this is a better solution because you are combining the two `Enumerators` to get the desired output.
If you don’t pass a block of code to `partition`, it returns an `Enumerator` object instead. `Enumerators` have a `with_index` method that will maintain the current loop index.
Problem
I'm looking for an elegant way to partition an array by using index in ruby eg: ``` ["a","b",3,"c",5].partition_with_index(2) => [["a","b",3],["c",5]] ``` So far the best that I can think is using the below ``` ["a","b",3,"c",5].partition.each_with_index{|val,index| index <= 2} => [["a","b",3],["c",5]] ``` Is there any other elegant way to accomplish this? Thanks!