I´m new to rails an i try to read a txt.file that looks like this:
ThomasLinde ; PeterParker ; Monday
JulkoAndrovic ; KeludowigFrau ; Tuesday
JohannesWoellenstein ; SiegmundoKrugmando ; Wednesday
Now i want to read each "column" of the .txt file to display it on a page of my application. My idea for the code looks like this:
if (File.exist?("Zuordnung_x.txt"))
fi=File.open("Zuordnung_x.txt", "r")
fi.each { |line|
sa=line.split(";")
@nanny_name=sa[0]
@customer_name=sa[1]
@period_name=sa[2]
}
fi.close
else
@nanny_name=nil
@customer_name=nil
@period_name=nil
flash.now[:not_available] = "Nothing happened!"
end
This is my Idea but he gives me only one line. Any ideas? or i am just able to read one line if i use @nanny_name
?
You can only need a variable with an array value, and push every line to it.
@result = []
if (File.exist?("Zuordnung_x.txt"))
fi=File.open("Zuordnung_x.txt", "r")
fi.each do |line|
sa=line.split(";")
@result << {nanny_name: sa[0], customer_name: sa[1], period_name: [2]}
end
fi.close
else
flash.now[:not_available] = "Nothing happened!"
end
and on view template, you need to each @result
, example
<% @result.each do |row| %>
<p><%= "#{row[:nanny_name]} serve the customer #{row[:customer_name]} on #{row[:period_name]}" %><p>
<% end %>
optional :
If just using split
, probably you will get some string with whitespace at the beginning of string or at the end of string
"ThomasLinde ; PeterParker ; Monday".split(';')
=> ["ThomasLinde ", " PeterParker ", " Monday"]
to handle it, you need strip
every value of an array like this :
"ThomasLinde ; PeterParker ; Monday".split(';').map(&:strip)
=> ["ThomasLinde", "PeterParker", "Monday"]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.