-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcsv.rb
More file actions
78 lines (65 loc) · 1.68 KB
/
csv.rb
File metadata and controls
78 lines (65 loc) · 1.68 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
# import ruby's standard csv library
require "csv"
class CSVMethods
# prints multiple files
def readFiles(files)
files.each_with_index do |book, index|
puts "Printing details of book #{index+1}"
CSV.foreach(book, headers: true) do |row|
print "#{row}"
end
print "\n"
end
end
# writes a file
def writeOpen(files)
files.each do |file|
CSV.open(file, 'w') do |row|
row << ['Name', 'Age', 'City']
row << ['Alice', 25, 'London']
end
end
end
# reads a file by opening it
def readOpen(*files)
files.each do |file|
print "Reading file using 'open' #{file}: \n"
CSV.open(file, 'r') do |el|
el.each do |row|
print "#{row} \n"
end
end
end
end
# create a csv file using array
def create_csv_array(arr, file_loc)
CSV.open(file_loc, 'w') do |csv|
arr.each do |element|
csv << element
end
end
end
# read into table
def tableMethod(files)
files.each do |file|
table = CSV.table(file)
puts table[:name]
end
end
end
s1 = CSVMethods.new
s1.readFiles(ARGV)
arr = [
["Name", "Age", "City"],
["Alice", 25, "London"],
["Bob", 30, "Paris"],
["Charlie", 22, "New York"],
["Diana", 28, "Tokyo"]
]
s1.readFiles(["csv_files\\book1.csv", "csv_files\\book2.csv", "csv_files\\book3.csv"])
s1.writeOpen(["csv_files\\book4.csv"])
s1.readFiles(["csv_files\\book4.csv"])
s1.readOpen("csv_files\\book1.csv", "csv_files\\book2.csv", "csv_files\\book3.csv")
s1.create_csv_array(arr, "csv_files\\generated_with_array.csv");
s1.readOpen("csv_files\\generated_with_array.csv")
s1.tableMethod(["csv_files\\generated_with_array.csv"])