Stop parsing when hitting an empty line - ruby-on-rails

I have a Rails app parsing incoming e-mails on Heroku using the Cloud-mailin add-on. The app recieves a list of prices in an e-mail and inserts them into the database.
This works fine, but if the e-mail contains for instance a signature in the bottom the code fails because it's also trying to parse that text.
Therefor I would like to rewrite the below parsing code to stop when it hits an empty line in the e-mail. All the price data is always at the top of the e-mail.
email_text = params[:plain]
email_text_array = []
email_text.split("\n").each do |email_line|
email_text_array << email_line.split(" ")
end
How do I change the above to stop when it hits an empty line in the email_taxt variable?
Thanks!

You can add a break :
email_text.split("\n").each do |email_line|
break if email_line.blank? # ends loop on first empty line
email_text_array << email_line.split(" ")
end

Does this question help: Is there a "do ... while" loop in Ruby?
Edit 1:
From the above article I think something like this would work:
email_text.split("\n").each do |email_line|
break if email_line.length < 1
email_text_array << email_line.split(" ")
end

Related

How to wait for all Concurrent::Promise in an array to finish/resolve

#some_instance_var = Concurrent::Hash.new
(0...some.length).each do |idx|
fetch_requests[idx] = Concurrent::Promise.execute do
response = HTTP.get(EXTDATA_URL)
if response.status.success?
... # update #some_instance_var
end
# We're going to disregard GET failures here.
puts "I'm here"
end
end
Concurrent::Promise.all?(fetch_requests).execute.wait # let threads finish gathering all of the unique posts first
puts "how am i out already"
When I run this, the bottom line prints first, so it's not doing what I want of waiting for all the threads in the array to finish its work first, hence I keep getting an empty #some_instance_var to work with below this code. What am I writing wrong?
Never mind, I fixed this. That setup is correct, I just had to use the splat operator * for my fetch_requests array inside the all?().
Concurrent::Promise.all?(*fetch_requests).execute.wait
I guess it wanted multiple args instead of one array.

How to detect if a field contains a character in Lua

I'm trying to modify an existing lua script that cleans up subtitle data in Aegisub.
I want to add the ability to delete lines that contain the symbol "♪"
Here is the code I want to modify:
-- delete commented or empty lines
function noemptycom(subs,sel)
progress("Deleting commented/empty lines")
noecom_sel={}
for s=#sel,1,-1 do
line=subs[sel[s]]
if line.comment or line.text=="" then
for z,i in ipairs(noecom_sel) do noecom_sel[z]=i-1 end
subs.delete(sel[s])
else
table.insert(noecom_sel,sel[s])
end
end
return noecom_sel
end
I really have no idea what I'm doing here, but I know a little SQL and LUA apparently uses the IN keyword as well, so I tried modifying the IF line to this
if line.text in (♪) then
Needless to say, it didn't work. Is there a simple way to do this in LUA? I've seen some threads about the string.match() & string.find() functions, but I wouldn't know where to start trying to put that code together. What's the easiest way for someone with zero knowledge of Lua?
in is only used in the generic for loop. Your if line.text in (♪) then is no valid Lua syntax.
Something like
if line.comment or line.text == "" or line.text:find("\u{266A}") then
Should work.
In Lua every string have the string functions as methods attached.
So use gsub() on your string variable in loop like...
('Text with ♪ sign in text'):gsub('(♪)','note')
...thats replace the sign and output is...
Text with note sign in text
...instead of replacing it with 'note' an empty '' deletes it.
gsub() is returning 2 values.
First: The string with or without changes
Second: A number that tells how often the pattern matches
So second return value can be used for conditions or success.
( 0 stands for "pattern not found" )
So lets check above with...
local str,rc=('Text with strange ♪ sign in text'):gsub('(♪)','notation')
if rc~=0 then
print('Replaced ',rc,'times, changed to: ',str)
end
-- output
-- Replaced 1 times, changed to: Text with strange notation sign in text
And finally only detect, no change made...
local str,rc=('Text with strange ♪ sign in text'):gsub('(♪)','%1')
if rc~=0 then
print('Found ',rc,'times, Text is: ',str)
end
-- output is...
-- Found 1 times, Text is: Text with strange ♪ sign in text
The %1 holds what '(♪)' found.
So ♪ is replaced with ♪.
And only rc is used as a condition for further handling.

How to find a specific word in string with Ruby/Rails

I got a few string like so:
TFjyg9780878_867978-DGB097908-78679iuhi698_widesky_light_87689uiyhk
AND
TFjyg9780878_867978-DGB097908-78679iuhi698_sky_light_87689uiyhk
AND
TFjyg9780878_867978-DGB097908-78679iuhi698_widesky_dark_87689uiyhk
AND
TFjyg9780878_867978-DGB097908-78679iuhi698_sky_dark_87689uiyhk
I need to check whether the strings above has one of the widesky_light, sky_light, widesky_dark and sky_dark with exactitude so I wrote this:
if my_string.match("widesky_light")
...
end
For each variant, but the problem I'm having is because sky_light and widesky_light are similar, my code is not working properly. I believe the solution to the above would be a regex, but I've spend the afternoon yesterday trying to get it to work without much success.
Any suggestions?
EDIT
A caveat: in this string (as example): TFjyg9780878_867978-DGB097908-78679iuhi698_widesky_light_87689uiyhk, the part after widesky_light, which is _87689uiyhk is optional, meaning that sometimes I have it, sometimes I don't, so a solution would not be able to count on _string_.
Looks like you just need to reorder your if statements
if my_string.match(/widesky_light/)
return 'something'
end
if my_string.match(/sky_light/)
return 'something'
end
Regex
1st regex : extract word for further checking
Here's a regex which only matches the interesting part :
(?<=_)[a-z_]+(?=(?:_|\b))
It means lowercase word with possible underscore inside, between 2 underscores or after 1 underscore and before a word boundary.
If you need some logic depending on the case (widesky, sky, light or dark), you could use this solution.
Here in action.
2nd regex : direct check if one of 4 words is present
If you just want to know if any of the 4 cases is present :
(?<=_)(?:wide)?sky_(?:dark|light)(?=(?:_|\b))
Here in action, with either _something_after or nothing.
Case statement
list = %w(
TFjyg9780878_867978-DGB097908-78679iuhi698_widesky_light_87689uiyhk
TFjyg9780878_867978-DGB097908-78679iuhi698_sky_light_87689uiyhk
TFjyg9780878_867978-DGB097908-78679iuhi698_widesky_dark_87689uiyhk
TFjyg9780878_867978-DGB097908-78679iuhi698_sky_dark_87689uiyhk
TFjyg9780878_867978-DGB097908-78679iuhi698_trash_dark_87689uiyhk
)
list.each do |string|
case string
when /widesky_light/ then puts "widesky light found!"
when /sky_light/ then puts "sky light found!"
when /widesky_dark/ then puts "widesky dark found!"
when /sky_dark/ then puts "sky dark found!"
else puts "Nothing found!"
end
end
In this order, the case statement should be fine. widesky_dark won't match twice, for example.
Maybe something like this:
case my_string
when /_(sky_light)/
# just sky_light
when /sky_light/
# widesky_light
when /_(sky_dark)/
# just sky_dark
when /sky_dark/
# widesky_dark
else
puts "I don't like"
end

How do I add a config list am I doing it wrongly?

The issue I am recieving is making a txt files contents readable in a listed format
such as:
word1
word2
word3
if a user were to have said any of the words/or phrases then they would get a response otherwise the program would wait for a valid reply from the blacklisted word file.
local valid;
repeat
local reply = io.read()
file = io.open('blacklist.txt', "r+")
file:read()
file:close()
-- list would equal contents within blacklist.txt
if reply == list then
valid = reply
print("Kicking User From Game")
--game.kick.saidUser
else
--do nothing and wait for valid response
end
until valid;
file:read() reads one line from the file and discards it.
I think you want to read the whole contents of the file into list with
list = file:read("*a")
Then you want to check whether reply is in the list with
if list:match("\n"..reply.."\n") then
You may want to read the list outside the loop and to prepend \n to list to make the pattern matching simpler.

changing a variable using gets.chomp()

im trying to write to a file using this code:
puts "-------------------- TEXT-EDITOR --------------------"
def tor(old_text)
old_text = gets.chomp #
end
$epic=""
def torr(input)
tore= $epic += input + ", "
File.open("tor.txt", "w") do |write|
write.puts tore
end
end
loop do
output = tor(output)
torr(output)
end
i have read the ultimate guide to ruby programming
and it says if i want to make a new line using in the file im writing to using File.open
i must use "line one", "line two
how can i make this happend using gets.chomp()? try my code and you will see what i mean
thank you.
The gets method will bring in any amount of text but it will terminate when you hit 'Enter' (or once the STDIN receives \n). This input record separator is stored in the global variable $/. If you change the input separator in your script, the gets method will actually trade the 'Enter' key for whatever you changed the global variable to.
$/ = 'EOF' # Or any other string
lines = gets.chomp
> This is
> multilined
> textEOF
lines #=> 'This is\nmultilined\ntext'
Enter whatever you want and then type 'EOF' at the end. Once it 'sees' EOF, it'll terminate the gets method. The chomp method will actually strip off the string 'EOF' from the end.
Then write this to your text file and the \n will translate into new lines.
File.open('newlines.txt', 'w') {|f| f.puts lines}
newlines.txt:
This is
multilined
text
If you dont use .chomp() the \n character will be added whenever you write a new line, if you save this to the file it also will have a new line. .chomp() removes those escape characters from the end of the input.
If this doesnt answer your question, i am sorry i dont understand it.

Resources