Store data from an array in a variable

Asked

Viewed 153 times

0

I have a CSV file with the information as below:

nome;cpf;ano;faculdade;
Pedro Sampaio;45896588963;2010;fmu;
Yuri Martins;45885485896;2012;uninove;
Pablo Vittar;32585296363;2020;unip;

I read this file using the code below, to get only the name "Pedro Sampaio"

require "csv"
path = "importador.csv"
option = { :encoding => "UTF-8", :skip_blanks => true, col_sep: "," }
array_students = CSV.read(path, options)
puts array_students[1][0][0..12]

I tried to use CSV.foreach but I could not reach the result of locating only the name as I did with read, but I know that each person can have a name bigger or smaller than Pedro Sampaio and I’m having difficulty to pick the name and add in a variable.

1 answer

0


According to your answer you already have an array where the Indice [0] comes all the contents of the CSV, right?

What you need to do is, turn it into an array and then separate it into blocks.

How to do this?

You will first transform the content of the array_students[0] into an array using the split()

arrays = array_students[0].split(";")

and then separate this array into blocks of 4

arrays = arrays.each_slice(4).to_a

With this, you can use a for to traverse this array with each line of csv, to display the student name, for example.

for student in arrays do
    puts student[0]
end

And the result would be:

name
Pedro Sampaio
Yuri Martins
Pablo Vittar

that you can use as you wish by saving the student[0] in a variable or other list.

Here at this link you can check the code running
https://repl.it/repls/CheerfulRegalDiskdrive

  • Maybe I didn’t quite understand your explanation, I’ll put what I did as an answer because size is not allowed here.

  • I updated the response and put a link with the code for you to see how it was done.

  • ah, its form became much simpler, after a conference I managed to reach a solution but with much more code. I will also share here: https://repl.it/@seuvitoo/reader

Browser other questions tagged

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