开发者

Quick Advice: How should this be written in Ruby?

开发者 https://www.devze.com 2022-12-18 00:16 出处:网络
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:

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


lines = str.split($/)
start_index = 1 + lines.find_index {|l| l.size > 15 }
lines[start_index..-1].each do |l|
  do_something(l)
end
0

精彩评论

暂无评论...
验证码 换一张
取 消