I am a Java/C++ programmer and Ruby is my first scripting language. I sometimes find that I am not using it as productively as I could in some areas, like this one for example:
Objective: to parse only certain lines from a file. The pattern I am going with is that there is one very large line with a size greater than 15, the rest are definitely smaller. I want to ignore all the lines before (and including) the large one.
def do_something(str)
puts str
end
str =
'ignore me
me too!
LARGE LINE ahahahahha its a line!
target1
target2
target3'
flag1 = nil
str.each_line do |line|
do_something(line) if flag1
flag1 = 1 if line.size > 15
end
I wrote this, but I think it could be written a lot better, ie, there must be a better way than setting a flag. Recommendations for how to write beautiful lines of Ruby also welcome.
Note/Clarification: I need to print ALL lines AFTER the first appearance of the LARGE LINE.
str.lines.drop_while {|l| l.length < 15 }.drop(1).each {|l| do_something(l) }
I like this, because if you read it from left to right, it reads almost exactly like your original description:
Split the string in lines and drop lines shorter than 15 characters. Then drop another line (i.e. the first one with more than 14 characters). Then do something with each remaining line.
You don't even need to necessarily understand Ruby, or programming at all to be able to verify whether this is correct.
require 'enumerator' # Not needed in Ruby 1.9
str.each_line.inject( false ) do |flag, line|
do_something( line ) if flag
flag || line.size > 15
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With