[英]How can i Read a file in Ruby on Rails
I´m new to rails an i try to read a txt.file that looks like this: 我是rails的新手,我试着读取一个如下所示的txt.file:
ThomasLinde ;
托马斯林德; PeterParker ;
彼得帕克; Monday
星期一
JulkoAndrovic ;
JulkoAndrovic; KeludowigFrau ;
KeludowigFrau; Tuesday
星期二
JohannesWoellenstein ;
JohannesWoellenstein; SiegmundoKrugmando ;
SiegmundoKrugmando; Wednesday
星期三
Now i want to read each "column" of the .txt file to display it on a page of my application. 现在我想读取.txt文件的每个“列”,以在我的应用程序的页面上显示它。 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
? 或者如果我使用
@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
,例子
<% @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 如果只使用
split
,可能会在字符串的开头或字符串的结尾处获得一些带有空格的字符串
"ThomasLinde ; PeterParker ; Monday".split(';')
=> ["ThomasLinde ", " PeterParker ", " Monday"]
to handle it, you need strip
every value of an array like this : 要处理它,你需要
strip
数组的每个值,如下所示:
"ThomasLinde ; PeterParker ; Monday".split(';').map(&:strip)
=> ["ThomasLinde", "PeterParker", "Monday"]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.