Extract a new array from an array - Ruby

Asked

Viewed 426 times

1

I have the following exit:

   => [
        [ 0] [
            [0] "CELULA",
            [1] "LENNA                                 ",
            [4] "jul 01",
            [5] " 2015 12:00:00 AM",
            [6] "N",
        ],
        [ 1] [
            [0] "CELULA",
            [1] "ARI
            [4] "jul 01",
            [5] " 2015 12:00:00 AM",
            [6] "P",
        ],
        ...
     ]

I need a new array similar to this one only with the items [1] and [6] of this array.

=> [
        [ 0] [
            [0] "LENNA                                 ",
            [1] "N",
        ],
        [ 1] [
            [0] "ARI
            [1] "P",
        ],
       ...
     ]
  • Could format the data better?

2 answers

1


We can simplify the code a little bit and leave more "ruby like" :

[["CELULA", "LENNA", "JUL 01", "2015 12:00:00 AM", "N"], ["CELULA", "ARI", "JUL 01", "2015 12:00:00 AM", "P"]].map {|e| [e[1], e[4]] }

[["LENNA", "N"], ["ARI", "P"]]

Basically we create a new Array extracting only the second (index 1) and the fifth (index 4) elements of the Array.

  • 1

    Heeey @Luizcarvalho Very good! I was trying something like this! but it never worked because I didn’t remember to put the elements inside a new array {|e| [ [elementos] ] }. Thank you very much for replying!

  • opa @Aristotle Coutinho for nothing! If the answer was helpful gives an upvote there to encourage the crowd to continue answering! big hug!

0

It’s important to leave the code of what you tried to do so the staff will be more motivated to help you.

However, here comes the code that gives you more or less what you need:

dados = [["CELULA", "LENNA", "JUL 01", "2015 12:00:00 AM", "N"], ["CELULA", "ARI", "JUL 01", "2015 12:00:00 AM", "P"]]
novo_array = []

dados.each do |x|
  array_filho = []
  array_filho.push(x[1])
  array_filho.push(x.last)

  novo_array.push(array_filho)
end

p novo_array

What has been done?

  • We traverse the array dados. And for each element found in this array (which is another array), we create a new array, with the elements of the second and last position of the array found within the array dados.

  • Add the created array (array_filho) in the novo_array

  • Thanks @psantos . Sorry I didn’t post what I had already tried. But all I could do was using the method map and always returned a new array with the values in single index. I had already found another solution, but for the purpose of study I wanted to know how would be the solution as I thought and I could not do rsrs. Vlw!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.