1

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"]
]

1 Answer 1

2

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"]]
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.