artists = [1, 2, 3]
column_1 = artists[0..artists.size/2]
column_2 = artists[artists.size/2+1..artists.size]
Refactorings
No refactoring yet !
Maciej Piechotka
August 14, 2008, August 14, 2008 13:41, permalink
Something like that (a bit different rounding):
artists = [1, 2, 3] column_1 = artists[0, artists.size/2] column_2 = artists[artists.size/2...artists.size]
Maciej Piechotka
August 14, 2008, August 14, 2008 13:45, permalink
The same rounding:
artists = [1, 2, 3] column_1 = artists[0...(artists.size/2.0).ceil] column_2 = artists[(artists.size/2.0).ceil...artists.size]
Adam
August 14, 2008, August 14, 2008 14:03, permalink
require "enumerator" artists = [ 1, 2, 3 ] column_1, column_2 = artists.enum_slice((artists.size / 2.0).round).to_a
gudata
August 15, 2008, August 15, 2008 11:33, permalink
thanks for the (artists.size / 2.0).round array and the enumeration idea
artists = [1, 2, 3] column_1 = artists[0, (artists.size/2.0).round] column_2 = artists - column_1
gudata
August 15, 2008, August 15, 2008 12:11, permalink
works for any size of the array
irb(main):001:0> column_1 = [1,2,3,4,5,6] => [1, 2, 3, 4, 5, 6] irb(main):003:0> column_2 = column_1.slice!((column_1.size/2.0).round..column_1.size) => [4, 5, 6] irb(main):004:0> column_1 => [1, 2, 3]
Vsevolod
August 20, 2008, August 20, 2008 20:08, permalink
artists = [1, 2, 3] column_2 = (column_1 = artists.dup).slice!(0, artists.size/2)
gfarfl
December 8, 2008, December 08, 2008 11:07, permalink
artists = [1, 2, 3, 4, 5, 6]
column1, column2 = artists.partition {|artist| artist <= artists.size }
Britto
September 29, 2010, September 29, 2010 20:06, permalink
using Array.drop
list = [1, 2, 3, 4, 5, 6, 7] half = list.size/2 part_1, part_2 = list[0, half], list.drop(half)
dcadenas.blogspot.com
October 2, 2010, October 02, 2010 15:07, permalink
If you are going to use this everywhere on many arrays on different places, it makes sense to extend Array:
class Array def split_in_two(first_chunk_size = self.size / 2) [self[0..first_chunk_size - 1], self[first_chunk_size..-1]] end end [1, 2, 3, 4, 5, 6].split_in_two > [[1, 2, 3], [4, 5, 6]] [1, 2, 3, 4, 5, 6, 7].split_in_two > [[1, 2, 3], [4, 5, 6, 7]] [1, 2, 3, 4, 5, 6, 7].split_in_two(5) > [[1, 2, 3, 4, 5], [6, 7]]
The example works if the array has more than 2 elements - this is defect not a feature :)