Changes

Jump to: navigation, search

Ruby Ranges

1,247 bytes added, 20:38, 20 November 2007
Using Range Methods
== Using Range Methods ==
Given the object-oriented nature of Ruby it should come as no surprise to you that a range is actually an object. As such, there are a number of methods of the Range class which can be accessed to interrogate and manipulate work with a range object.
<pre>
Hello caq
Hello car
</pre>
== Ruby Ranges as Conditional Expressions ==
 
Ruby Ranges can also be used as conditional expressions in looping conditions. The range start value represents the start of the of loop, which runs until the range end marker is detected.
 
<pre>
while input = gets
puts input + " triggered" if input =~ /start/ .. input =~ /end/
end
</pre>
 
== Ruby Range Intervals ==
 
Ranges are ideal for identifying if a value falls within a particular range. For example, we might want to know whether a number is within a certain range, or a character within a certain group of letters arranged in alphabetical order. This is achieved using the === equality operator:
 
<pre>
(1..20) === 15 # Does the number fit in the range 1 to 20
=> true
('k'..'z') === 'm' # Does the letter fall between the letters 'k' and 'z' in the alphabet?
=> true
</pre>
 
== Ranges in case Statements ==
 
Ranges are perhaps at their most powerful when they are used in conjunction with a ''case'' statement
(for more information see [[The Ruby case Statement]] chapter:
 
<pre>
score = 70
 
result = case score
when 0..40: "Fail"
when 41..60: "Pass"
when 61..70: "Pass with Merit"
when 71..100: "Pass with Distinction"
else "Invalid Score"
end
 
puts result
</pre>

Navigation menu