0

Im new on the ruby on rails How can i read datas from csv files? I have a csv file, and it has datas like name surname etc.

Here, there is a name surname variables. I need to read from csv files. How can i do it?

my codes now like this:

require 'csv'

table = CSV.parse(File.read("csv files/department.csv"), headers: true)

class Person
    @name
    @surname
    @role
    @department
    def printPersonFullname(name, surname)
        @name = name
        @surname = surname
        puts ("#{@name} #{@surname}")
    end
end

here csv file image:

enter image description here

By the way, when i print, console print this: D:\Ruby27-x64\bin\ruby.exe: No such file or directory -- csv.rb (LoadError)

2
  • Exactly where is located your code for the csv processing? and how is it executed? Commented Aug 21, 2021 at 15:44
  • They are in lib/tasks/csv files. It is csv file, there are rows like name,surname etc. ,and there are columns which has data like Efe Şahin Commented Aug 21, 2021 at 15:48

1 Answer 1

1

Here goes a working example of reading CSV, instantiating Person object and printing.

# following the directory tree:
#   ./
#   ./tasks/main.rb
#   ./csv/department.csv
#
# csv file example
#
# name,surname,department
# John,Doe,IT
# Bill,Doe,IT
#
# running this code:
#   ruby tasks/main.rb
require 'csv'

class Person
  def initialize(name, surname, department)
    @name = name
    @surname = surname
    @department = department
  end

  def print_full_name
    puts "#{@name} #{@surname}"
  end
end

### main
filepath = "#{__dir__}/../csv/department.csv"
CSV.foreach(filepath, headers: true) do |row|
  person = Person.new(
    row["name"],
    row["surname"],
    row["department"]
  )

  person.print_full_name
end

Your code in the question wasn't written in ruby way. I recommend you to read this ruby styleguide to follow some practices on our community

Sign up to request clarification or add additional context in comments.

Comments

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.