r/learnruby • • Mar 22 '14
Splitting an array up into seperate arrays based on is_a?
I think I need help. I keep trying to figure out how to iterate through an array and split it up into two seperate arrays, but I can't. I have the following araray.
[1,2,R,3,4,R,5,6,R,7,8,R,9,10,R,11,12,R,13,14,R,15,16,R,17,18,R,19,20]
I want to split the numbers up into one array and put the "R"s iup into another, but I can't figure out how to do it. Maybeusing is_a? Does anyone have any ideas?
2
Upvotes
6
u/materialdesigner Mar 22 '14
my_array.partition { |elem| elem.is_a?(Integer) }Enumerable#partition
2
u/UkuleleBaller Mar 24 '14 edited Mar 24 '14
I'm new to ruby myself but the following should work:
edit: cleaned up the formatting + tested in netbeans, this should give you your solution!
1
u/herminator Mar 22 '14
Something like
my_array.group_by { |item| item.class }and then extract the lists from the resulting hash?