Ranges

View saved

Create ranges

.. includes the end; ... excludes it.

puts (1..3).to_a.inspect
puts (1...3).to_a.inspect

Use ranges in case

Ranges make numeric bands easy.

score = 82
puts case score
     when 90..100 then "excellent"
     when 70...90 then "ok"
     else "practice"
     end

Iterate a range

Ranges are Enumerable.

("a".."c").each { |ch| puts ch }

Range tips

  • Convert to an array only when you need one
  • Huge ranges should be iterated, not expanded carelessly
  • Membership uses cover? or include?
  • Date ranges appear often in real apps

Comments

One comment per signed-in account. Comments are saved with this page’s URL.