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"]
Related
So, I have the following:
twodarray = []
File.open("SG_hum50_LODG.gro", "r") do |f|
f.each_line do |line|
textarray = line.split()
textarray[0],textarray[1],textarray[2] = textarray[1],textarray[0],textarray[2].to_i
textarray[1] = textarray[1].gsub(/:/, '').to_i
twodarray << textarray
end
end
Which works pretty well. The problem I am having is I need to ignore the last line of the text file, and I need to add
["Sensor", "Timestamp", "Sensor Value"],
As the first row in the array.
I would do this
twodarray = [["Sensor", "Timestamp", "Sensor Value"]]
File.open("SG_hum50_LODG.gro", "r") do |f|
f.each_line do |line|
textarray = line.split()
textarray[0], textarray[1], textarray[2] =textarray[1], textarray[0], textarray[2].to_i
textarray[1].gsub!(/:/, '').to_i
twodarray << textarray
end
end
twodarray.pop
twodarray << textarray unless line[f.last]
Code
def read_sensor_data(fname, first_arr)
File.open(fname, "r") do |f|
f.each_line.with_object([first_arr]) do |line, arr|
next if f.eof?
sensor, time, value, *rest = line.split
arr << [time.delete(':').to_i, sensor, value.to_i, *rest]
end
end
end
*rest is not needed if every line of the file contains no more than three words.
Example
FName = "demo"
Create a file.
File.write FName,
<<-_
heat 10:21 16
sound 11:45 74
That's all, folks!
_
#=> 49
Check the file.
puts File.read FName
heat 10:21 16
sound 11:45 74
That's all, folks!
Try the method.
read_sensor_data FName, ["Sensor", "Timestamp", "Sensor Value"]
#=> [["Sensor", "Timestamp", "Sensor Value"],
# [1021, "heat", 16],
# [1145, "sound", 74]]
Be careful aggregating lines in a file into an array because that's not a scalable solution. Only do it if you can guarantee that the file being loaded, plus the needs of your script, will never grow beyond the available free memory.
Your question isn't clear about what you're trying to do, but it sounds like you're trying to modify a file on disk, which is easily done using File.foreach to read the incoming file line-by-line.
There's a couple ways to ignore the last line, but the easiest is to count the lines in the file then read all but the last line. There are many ways to count the lines in a file, the easiest is to use the *nix wc -l command, which is designed to do it:
lines_in_file = `wc -l /path/to/file`.to_i
and for a pure Ruby solution I'd do something like this:
lines_in_file = File.foreach('input.txt').inject(0){ |i, _| i + 1 }
Then it's a simple matter of counting lines_in_file - 1 lines. This is untested but it looks about right:
INPUT_FILE = 'input.txt'
lines_in_file = File.foreach(INPUT_FILE).inject(0){ |i, _| i + 1 }
File.open('output.txt', 'w') do |fo|
fo.puts '"Sensor", "Timestamp", "Sensor Value"'
File.foreach(INPUT_FILE) do |li|
fo.puts li
break if $. == (lines_in_file - 1)
end
end
I try to write to an string something like this:
arr << "Icd3code.create!({:text => '#{variable1}'})" + "\n"
My problem is that variable 1 is an string, that contains an ' :
variable1 = "Ami's house"
So that at the end the ouput of my code is this:
Icd3code.create!({:text => 'Ami's house'})
How you can see now i have one ' to much! I dont know what i can do to avoid this problem! Thanks
If I've understood, you want to loop over some input, building up a list of parameters, which you plan to later use to create some records. If that's the case, I think you're better off using hashes, instead of strings:
# Let's pretend this came from the big, bad, world
inputs = ["Ami's house", "Fred's house", "Jim's house"]
creation_params = []
inputs.each do |input|
creation_params << {:text => input}
end
Then you could create all the Icd3codes, like this:
creation_params.each do |params|
Icd3code.create!(params)
end
Or you could save them in a text file, for later:
File.open('dest', 'w') do |f|
f.write(creation_params.to_json)
end
variable1 = "Ami's house"
puts %Q[Icd3code.create!({:text => "#{variable1}"})] + "\n"
--output:--
Icd3code.create!({:text => "Ami's house"})
I'm newbie on rails.
In my form I get string like "123, xxx_new item, 132, xxx_test "
if the item start with "xxx_" than its mean that i should add the item to the db otherwise enter the value
this is my code and i sure that there is a better way to write this code
tags = params[:station][:tag_ids].split(",")
params[:station][:tag_ids] = []
tags.each do |tag|
if tag[0,4] =="xxx_"
params[:station][:tag_ids] << Tag.create(:name => tag.gsub('xxx_', '')).id
else
params[:station][:tag_ids]<< tag
end
end
I'm looking for how to improve my code syntax
What about:
tags = params[:station][:tag_ids].split(',')
params[:station][:tag_ids] = tags.each_with_object([]) do |tag, array|
array << tag.start_with?('xxx_') ? Tag.create(name: tag[4..-1]).id : tag
end
I'm trying to have greentext support for my Rails imageboard (though it should be mentioned that this is strictly a Ruby problem, not a Rails problem)
basically, what my code does is:
1. chop up a post, line by line
2. look at the first character of each line. if it's a ">", start the greentexting
3. at the end of the line, close the greentexting
4. piece the lines back together
My code looks like this:
def filter_comment(c) #use for both OP's and comments
c1 = c.content
str1 = '<p class = "unkfunc">' #open greentext
str2 = '</p>' #close greentext
if c1 != nil
arr_lines = c1.split('\n') #split the text into lines
arr_lines.each do |a|
if a[0] == ">"
a.insert(0, str1) #add the greentext tag
a << str2 #close the greentext tag
end
end
c1 = ""
arr_lines.each do |a|
strtmp = '\n'
if arr_lines.index(a) == (arr_lines.size - 1) #recombine the lines into text
strtmp = ""
end
c1 += a + strtmp
end
c2 = c1.gsub("\n", '<br/>').html_safe
end
But for some reason, it isn't working! I'm having weird things where greentexting only works on the first line, and if you have greentext on the first line, normal text doesn't work on the second line!
Side note, may be your problem, without getting too in depth...
Try joining your array back together with join()
c1 = arr_lines.join('\n')
I think the problem lies with the spliting the lines in array.
names = "Alice \n Bob \n Eve"
names_a = names.split('\n')
=> ["Alice \n Bob \n Eve"]
Note the the string was not splited when \n was encountered.
Now lets try this
names = "Alice \n Bob \n Eve"
names_a = names.split(/\n/)
=> ["Alice ", " Bob ", " Eve"]
or This "\n" in double quotes. (thanks to Eric's Comment)
names = "Alice \n Bob \n Eve"
names_a = names.split("\n")
=> ["Alice ", " Bob ", " Eve"]
This got split in array. now you can check and append the data you want
May be this is what you want.
def filter_comment(c) #use for both OP's and comments
c1 = c.content
str1 = '<p class = "unkfunc">' #open greentext
str2 = '</p>' #close greentext
if c1 != nil
arr_lines = c1.split(/\n/) #split the text into lines
arr_lines.each do |a|
if a[0] == ">"
a.insert(0, str1) #add the greentext tag
# Use a.insert id you want the existing ">" appended to it <p class = "unkfunc">>
# Or else just assign a[0] = str1
a << str2 #close the greentext tag
end
end
c1 = arr_lines.join('<br/>')
c2 = c1.html_safe
end
Hope this helps..!!
I'm suspecting that your problem is with your CSS (or maybe HTML), not the Ruby. Did the resulting HTML look correct to you?
I have a controller like this:
def download_link
#It starts a background process to handle all these things
temp_file = Tempfile.new 'temp_file'
temp_sqlite_db = SQLite3::Database.new temp_file.path
temp_sqlite_db.execute("CREATE TABLE inspection (id INTEGER NOT NULL,desc VARCHAR(255));")
inspections = Inspection.a_heavy_query_that_doesnt_worths_to_wait_so_much_for_a_reply
# Some code inserting records and creating tables, with execute() too
# more code, compressing the db and sending an email with a download link to the zip file
end
Now, I would like to know if there's a way to replace the execute() function and maybe create the tables and save records like inspection.create(something) . Thanks in advance
If anyone needs something similar, this was my implementation:
# config/initializers/sql_returner.rb
module ActiveRecord
class Base
def sql_insert
if attributes_with_quotes.empty?
connection.empty_insert_statement(self.class.table_name)
else
"INSERT INTO #{self.class.quoted_table_name} " +
"(#{quoted_column_names.join(', ')}) " +
"VALUES(#{attributes_with_quotes.values.join(', ')});"
end
end
def self.sql_create
"CREATE TABLE #{table_name} (" +
" #{ self.columns.collect{ |column|
column_sql = " #{ column.name } #{ sql_type column } "
column_sql << " PRIMARY KEY " if column.primary
column_sql << " NOT NULL " unless column.null
column_sql
}.join(', ') } );"
end
private
def self.sql_type column
case column.type
when 'datetime', 'string'
'TEXT'
else
column.type.to_s
end
end
end
end
Then, if I need to create tables and insert records, taking the same code of the question as example, I must to run:
def download_link
temp_file = Tempfile.new 'temp_file'
temp_sqlite_db = SQLite3::Database.new temp_file.path
temp_sqlite_db.execute(Inspection.sql_create)
inspections = Inspection.a_heavy_query_that_doesnt_worths_to_wait_so_much_for_a_reply
insert = ""
inspections.each{ |insp|
insert << insp.return_insert_sql
}
#.....
end
For the first method sql_insert I took as example the create method code of ActiveRecord. I know that maybe some kittens died coding this implementation, but at least for me it works.