Quick tip: how should this be written in Ruby?

I am a Java / C ++ programmer, and Ruby is my first scripting language. Sometimes it seems to me that I do not use it as productively as I could in some areas, for example, for example:

Purpose: to analyze only certain lines from a file. The sample I'm going to make is that there is one very large line with a size greater than 15, the rest are certainly smaller. I want to ignore all lines up to (and including) large.

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 can be written much better, i.e. There should be a better way than setting a flag. Recommendations on how to write beautiful Ruby lines are also welcome.

Note / Clarification: I need to print ALL lines after the first appearance of LARGE LINE.

+7
ruby coding-style
source share
3 answers
 str.lines.drop_while {|l| l.length < 15 }.drop(1).each {|l| do_something(l) } 

I like it because if you read it from left to right, it reads in much the same way as the original description:

Separate a line in lines and separate lines less than 15 characters long. Then discard another line (i.e., the first with more than 14 characters). Then do something with each remaining line.

You donโ€™t even have to understand Ruby or even program to check if this is correct.

+10
source share
 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 
+3
source share
 lines = str.split($/) start_index = 1 + lines.find_index {|l| l.size > 15 } lines[start_index..-1].each do |l| do_something(l) end 
+1
source share

All Articles