Extract a new array from an array - Ruby

1

I have the following output:

   => [
        [ 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 only with items [1] and [6] of this array.

=> [
        [ 0] [
            [0] "LENNA                                 ",
            [1] "N",
        ],
        [ 1] [
            [0] "ARI
            [1] "P",
        ],
       ...
     ]
    
asked by anonymous 22.01.2016 / 02:17

2 answers

1

We can simplify the code a 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]] }
  

[

11.02.2016 / 15:07
0

It's important to leave the code of what you tried to do so that the staff is more motivated to help you.

However, here's 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 did you do?

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

  • Add the created array ( array_filho ) in novo_array

22.01.2016 / 06:01