DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Ruby Ranges As Conditional Expressions

05.03.2010
| 3254 views |
  • submit to reddit
        Source: <a href="http://www.techotopia.com/index.php/Ruby_Ranges#Ruby_Range_Intervals">Ruby Ranges - Techotopia</a> [techotopia.com]
<snip>
Ruby Ranges can also be used as conditional expressions in looping conditions. The range start value represents the start of the loop, which runs until the range end marker is detected.
while input = gets
  puts input + " triggered" if input =~ /start/ .. input =~ /end/
end
</snip>
output (test performed within an IRB session):
<pre>
test
ready
go
do it
start
start
 triggered
fun fun fun
fun fun fun
 triggered
rest
rest
 triggered
that's enough
that's enough
 triggered
stop
stop
 triggered
end
end
 triggered
sigh
hello?
^CIRB::Abort: abort then interrupt!!
</pre>
Note: This syntax also works:
while input = gets
  puts input + " triggered" if input[/start/] .. input[/end/]
end