Forum: Ruby how to merge 2 elements within an array

73700e119917433681f2e8f3e4369f74?d=identicon&s=25 Li CN (alex-osu3)
on 2016-11-03 18:26
Hi all,

I have one array in this format:
array1=[
['a_1_1',1],
['a_1_2',2],
['a_1_3',2],
['a_2_1',1],
['b_1_1',1]
['c_1_1',1],
]

How do I change it into this format?
array2=[
['a_1_1 a_1_2 a_1_3',1],
['a_2_1',1],
['b_1_1',1]
['c_1_1',1],
]

element 0, 1, and 2 considered the same elements as they all contain
'a_1'


Thanks,
483ff328f3adc8bc6a31342eef0ba0c2?d=identicon&s=25 Sam Sepiol (samsepiol)
on 2016-11-05 01:59
array2 = array1.group_by { |arr| arr.first[0..2] }.map { |key, value|
[value.map(&:first).join(' '), value.first.last] }
0fa73332c8e4a3b06ea439fd3f034322?d=identicon&s=25 Ronald Fischer (rovf)
on 2016-11-07 14:35
The specification is a bit unclear. For instance, if the input were

array1=[
['a_1_1',1],
['a_2_1',1],
['b_1_1',1],
['a_1_2',2],
['c_1_1',1],
['a_1_3',2]
]

should the output be the same as in your original case?
73700e119917433681f2e8f3e4369f74?d=identicon&s=25 Li CN (alex-osu3)
on 2016-11-17 16:05
No need to be the same orders as long as a_1_1, a_1_2, a_1_3 can be
merged as a string divided by empty space.
0fa73332c8e4a3b06ea439fd3f034322?d=identicon&s=25 Ronald Fischer (rovf)
on 2016-11-17 16:20
And how do you determin the single digit in the output? I.e. why should
the resulting array be

   [['a_1_1 a_1_2 a_1_3',1],...]

and not

   [['a_1_1 a_1_2 a_1_3',2],...]

?
Please log in before posting. Registration is free and takes only a minute.
Existing account

NEW: Do you have a Google/GoogleMail, Yahoo or Facebook account? No registration required!
Log in with Google account | Log in with Yahoo account | Log in with Facebook account
No account? Register here.