Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Partition array using index in ruby

Tags:

ruby

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!

like image 294
Ignatius Monthy Avatar asked Jul 18 '13 15:07

Ignatius Monthy


Video Answer


4 Answers

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.

like image 115
nicosantangelo Avatar answered Nov 10 '22 01:11

nicosantangelo


Why don't you use array.slice!

array#slice! Deletes the element(s) given by an index (optionally up to length elements) or by a range.

> a = ['a', 'b', 'c', 5]
> b = a.slice! 0, 2 # => ['a', 'b'] 
> a # => ['c', 5]

In your case,

> [a.slice!(0, index), a]
like image 40
egghese Avatar answered Nov 10 '22 00:11

egghese


You could use Enumerable's take and drop methods:

a = ["a","b",3,"c",5]
[a.take(3), a.drop(3)]  # => [["a", "b", 3], ["c", 5]]

I made an Enumerable quick reference sheet you might want to consult for questions like this.

like image 24
David Grayson Avatar answered Nov 09 '22 23:11

David Grayson


This can be done, but not sure if it elegant or not :

a = ["a","b",3,"c",5]
index = 2
[a[0..index], a[index+1..-1]]

Thanks

like image 31
Mike Li Avatar answered Nov 10 '22 01:11

Mike Li