KevinOelen
KevinOelen

Reputation: 779

Parsing array to string from nested array

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

Upvotes: 1

Views: 508

Answers (1)

Arup Rakshit
Arup Rakshit

Reputation: 118299

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

Upvotes: 2

Related Questions