Question on the flip/flop op

Z

Zach Dennis

With the following code where 'f' is an file handle:

f.each_line{ |line|
header = 1 .. $.=~$^ ? true : false
body = $^ .. f.eof ? true : false }

Say body becomes true after the first \n. What is stopping header from
becoming true again on the next \n? Since it will be between 1 and the $^.
Is the flip flop op somehow storing that $^ was already reached and not to
test the condition again?

Thanks,

Zach
 
R

Robert Klemme

Zach Dennis said:
With the following code where 'f' is an file handle:

f.each_line{ |line|
header = 1 .. $.=~$^ ? true : false
body = $^ .. f.eof ? true : false }

First of all, you can use FF only in if statements. Then, using "?:" to
convert boolean values to boolean values is superfluous. And btw your code
doesn't compile for me.
Say body becomes true after the first \n. What is stopping header from
becoming true again on the next \n? Since it will be between 1 and the $^.
Is the flip flop op somehow storing that $^ was already reached and not to
test the condition again?

The behavior of the FF is like this: it's false until the first condition
matches. If that's the case it becomes true and stays true as long as the
second doesn't match. After that it's false until the first condition
matches again.

The easiest way to separate header and body of a file in mbox format is
possibly this:

io.each_line do |line|
line.chomp!

if /^From / =~ line .. /^$/ =~ line
puts "Header: " + line unless line.length == 0
else
puts "Body: " + line
end
end

Of course you will have to do more processing to treat individual header
lines and deal with continued header lines. You can look into gurgitate
mail to see how it does it.

http://rubyforge.org/projects/gurgitate-mail/

Regards

robert
 
M

Michael campbell

Robert said:
First of all, you can use FF only in if statements.

Do you mean "only as a scalar"? FF's work just fine in other statements; "while" comes to mind.
 
R

Robert Klemme

Michael campbell said:
Do you mean "only as a scalar"? FF's work just fine in other statements;
"while" comes to mind.

Well, yes. I should've included while and the like. But you can't use a FF
in "foo = /flip/ .. /flop/":

irb(main):013:0> foo = /flip/ .. /flop/
ArgumentError: bad value for range
from (irb):13

So ".." and "..." behave differently in a context like "if", "unless",
"while" etc.

Hope that cleared it up.

robert
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,768
Messages
2,569,574
Members
45,048
Latest member
verona

Latest Threads

Top