Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Quick Advice: How should this be written in Ruby?

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.

like image 368
Zombies Avatar asked Jan 22 '10 16:01

Zombies


2 Answers

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.

like image 177
Jörg W Mittag Avatar answered Sep 20 '22 00:09

Jörg W Mittag


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
like image 25
Farrel Avatar answered Sep 19 '22 00:09

Farrel