Array problem

a = [ [ ‘john’ , ‘195’ ] , [ ‘jack’ , ‘132’ ] ]

i need to convert this to:

b = [ [ ‘name’ , ‘john’ ] , [ ‘id’ , ‘195’ ] , [ ‘name2’ , ‘jack’ ] ,
[ ‘id2’ , ‘132’ ] ]

i am throwing a blank

b = Array.new
a.each do_with_index do | new, index |
b << [ ‘name#{index}’, new[0] ]
b << [ ‘id#{index}’, new[1] ]
end

does this make sense, can’t this be done with 1 line ?

On 26 Apr 2008, at 09:17, rushnosh wrote:

a = [ [ ‘john’ , ‘195’ ] , [ ‘jack’ , ‘132’ ] ]

i need to convert this to:

b = [ [ ‘name’ , ‘john’ ] , [ ‘id’ , ‘195’ ] , [ ‘name2’ , ‘jack’ ] ,
[ ‘id2’ , ‘132’ ] ]

a.inject([]) {| total , pair| total << [‘name’, pair.first] << [‘id’,
pair.last] }

Fred

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs