Ranges in Ruby
Two dots or three: Ruby's ranges count, test, step and slice.
puts (1..5).to_a.inspect
puts (1...5).to_a.inspect
puts ("a".."e").to_a.inspect
decade = 1990..1999
puts decade.include?(1995)
puts decade.sum
puts (0..100).step(25).to_a.inspect
# ranges also slice strings and arrays
puts "typestar"[0..3]
puts [10, 20, 30, 40][1..-1].inspect
How it works
1..5includes the end;1...5stops one short.- Ranges answer
include?andsumlike any enumerable. step(25)skips through; ranges also index strings and arrays.
Keywords and builtins used here
puts
The run, in numbers
- Lines
- 13
- Characters to type
- 279
- Tokens
- 93
- Three-star pace
- 85 tpm
At the three-star pace of 85 tokens a minute, this run takes about 66 seconds.
Step 3 of 3 in Collections, step 6 of 29 in Language basics.