The question about 'Range' as Condition

Hi All,

I don’t know why these two codes of behavior will not be the same,
in my opinion, they are the same logic.

Thanks a lot!

Codes:

arr = [ ‘head’, ‘start’, ‘body’, ‘end’, ‘tail’ ]

test 1

puts ‘loop test:’
for i in 0…arr.size
puts arr[i] if arr[i] =~ /start/ … arr[i] =~ /end/
end

puts

test 2

puts ‘hard test:’
puts arr[0] if arr[0] =~ /start/ … arr[0] =~ /end/
puts arr[1] if arr[1] =~ /start/ … arr[1] =~ /end/
puts arr[2] if arr[2] =~ /start/ … arr[2] =~ /end/
puts arr[3] if arr[3] =~ /start/ … arr[3] =~ /end/
puts arr[4] if arr[4] =~ /start/ … arr[4] =~ /end/

The output:

loop test:
start
body
end

hard test:
start

  • Haibin S.

On Tue, May 7, 2013 at 12:07 PM, Haibin S. [email protected] wrote:

Hi All,

I don’t know why these two codes of behavior will not be the same,
in my opinion, they are the same logic.

No, it’s not, because you change the number of range operators. A range
operator in an if / unless situation has a built in FlipFlop which will
change the state whenever a change in matching occurs:
http://www.ruby-doc.org/docs/ProgrammingRuby/html/tut_expressions.html#UF

Cheers

robert

Hi Robert,

Thanks in advance for your help!

No, it’s not, because you change the number of range operators.
But I still do not understand what’s the number of range operators.

Is the state of flip-flop only be kept within loop ?

Cheers

Haibin

On Tue, May 7, 2013 at 6:14 PM, Haibin S. [email protected] wrote:

No, it’s not, because you change the number of range operators.
But I still do not understand what’s the number of range operators.

Is the state of flip-flop only be kept within loop ?

No, the state is attached to a single source code location if you will
(and
per thread I believe). That’s why. In the first case you have 1
instance
in the second multiple.

Cheers

robert

Hi Robert,

I finally get to know!
Thanks again!

Cheers

Haibin