Skip to content

Instantly share code, notes, and snippets.

@Quemia
Last active April 21, 2020 22:09
Show Gist options
  • Select an option

  • Save Quemia/2c5f597d87f974654d10411407049930 to your computer and use it in GitHub Desktop.

Select an option

Save Quemia/2c5f597d87f974654d10411407049930 to your computer and use it in GitHub Desktop.

Range

Intervals as a sequence

The first and perhaps the most natural use of intervals is to express a sequence. Ruby creates these strings using the range operators:

".." - Creates an inclusive range. Ex:

     (1..5).to_a => 1,2,3,4,5
     ('a'..'d').to_a => 'a','b','c','d'

"..." - Create an interval that excludes the specified high value. Ex:

     (1...5).to_a => 1,2,3,4

Intervals can also be used as conditional expressions.

Ex:

while gets
    print if /star/../end/
end

  score = 70
  result = case score
    when 0..40 then "Fail"
    when 41..60 then "Pass"
    when 61..70 then "Pass with Merit"
    when 71..100 then "Pass with Distinction"
   else "Invalid Score"
   end

puts result
=> Pass wuith Merit  
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment