Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does this Ruby code work - if-stmt with ranges ?

Tags:

ruby

I'm currently learning Ruby and I can't seem to wrap around what if /start/../end does... Help?

while gets
  print if /start/../end/
end
like image 963
tina nyaa Avatar asked Aug 22 '26 18:08

tina nyaa


2 Answers

Since you mentioned that you're new to Ruby, it's first worth taking note that you're dealing with Regular Expressions (regex) in the example - anything that is delimited between two forward slashes:

/start/   # a regular expression literal

Regular Expressions are a powerful way of matching a certain combination of letters from a larger string.

"To start means to begin." =~ /start/  #=> true, because 'start' is in the string. 

The double dot notation is the flip-flop operator, a controversial construct probably inherited from Perl and not usually recommended to be used because it can lead to confusion.

It means the following: It will collectively evaluate to false until the left hand operand is true. At which point it will collectively evaluate to true. However it will only remain true until the right hand operand evaluates to true - at which point it will again evaluate collectively to false.

Using your above example therefore:

while gets
 print if /start/../end/
end
  1. Until 'start' is entered in, the entire expression is false, and nothing is printed.
  2. When 'start' is input, the entire expression is true, therefore EVERYTHING input after this point will also be printed out. (despite not being 'start')
  3. As soon as 'end' is input, the entire expression evaluates to false, and nothing from that point on is printed out.
like image 134
MeMory LEAk99 Avatar answered Aug 25 '26 07:08

MeMory LEAk99


It's called the flip-flop operator. You can read more at "Ruby flip-flop operator".

like image 32
Vasiliy Ermolovich Avatar answered Aug 25 '26 08:08

Vasiliy Ermolovich



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!