Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

Let's say I have nested array like:

nested = [
             [0.5623507523876472, ["h", "e", "l", "l", "o"]], 
             [0.07381531933500263, ["h", "a", "l", "l", "o"]], 
             [0.49993338806153054, ["n", "i", "h", "a", "o"]], 
             [0.6499234734532127, ["k", "o", "n", "n", "i", "c", "h", "i", "w", "a"]]
         ]

Initially I wanted to convert it into hash. But first I have to convert array(above example ["h", "e", "l", "l", "o"]) to "hello".

So my question is how to convert nested into :

[ 
   [0.5623507523876472, "hello"],
   [0.07381531933500263, "hallo"],
   [0.49993338806153054, "nihao"],
   [0.6499234734532127, "konnichiwa"]
]
share|improve this question

1 Answer 1

up vote 0 down vote accepted

If you don't want to destroy the source array nested :

Use Array#map :

nested = [
             [0.5623507523876472, ["h", "e", "l", "l", "o"]], 
             [0.07381531933500263, ["h", "a", "l", "l", "o"]], 
             [0.49993338806153054, ["n", "i", "h", "a", "o"]], 
             [0.6499234734532127, ["k", "o", "n", "n", "i", "c", "h", "i", "w", "a"]]
         ]

nested_map = nested.map { |a,b| [a,b.join] }
# => [[0.5623507523876472, "hello"],
#     [0.07381531933500263, "hallo"],
#     [0.49993338806153054, "nihao"],
#     [0.6499234734532127, "konnichiwa"]]

If you want to destroy the source array nested

Use Arry#map! method :

nested = [
             [0.5623507523876472, ["h", "e", "l", "l", "o"]], 
             [0.07381531933500263, ["h", "a", "l", "l", "o"]], 
             [0.49993338806153054, ["n", "i", "h", "a", "o"]], 
             [0.6499234734532127, ["k", "o", "n", "n", "i", "c", "h", "i", "w", "a"]]
         ]

nested.map! { |a,b| [a,b.join] }
# => [[0.5623507523876472, "hello"],
#     [0.07381531933500263, "hallo"],
#     [0.49993338806153054, "nihao"],
#     [0.6499234734532127, "konnichiwa"]]
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.