Reputation: 781
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:
By the way, when i print, console print this:
D:\Ruby27-x64\bin\ruby.exe: No such file or directory -- csv.rb (LoadError
)
Upvotes: 0
Views: 2522
Reputation: 412
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
Upvotes: 1