Intro to Ruby - Ranges

Ruby

Overview

Ranges (either a .. or … notation) were one of the first new concepts that pulled me into the language and kept me reading, excited to see what I could do with the language next. Yeah, I know, crazy to think that a person could be reading a programming book with the same intensity as a thriller novel but, hey, Ruby does have that affect on people.

The following shows off ranges. Oh, and don’t let the for loop confuse you, I’ll be talking about them more in future posts. Just concentrate on how easy it is to create a range and the simplicity of the syntax.

Code

# An inclusive range includes the beginning and ending number in the range.
puts "01 Inclusive Range \n\n"
for x in 1..5 do
puts x
end

# An exclusive range includes the beginning but NOT the ending number in the range.
puts "\n02 Exclusive Range\n\n"
for x in 1...5 do
puts x
end

# Ranges can be used to extract portions of a string. In this example we pull the "ruby" word out of the string.
puts "\n03 Ranges used in a string.\n\n"
message = "My little ruby string."
puts message[10..14]

Output

01 Inclusive Range

1
2
3
4
5

02 Exclusive Range

1
2
3
4

03 Ranges used in a string.

ruby

Download

The code above is provided as a Ruby script so that you can quickly execute all the examples above if you like. Just download, unzip, and type the following to execute all examples via the command line: ruby 03-ranges.rb.

What’s Next

Arrays.

Tags:

Friday, February 20th, 2009 Software

No comments yet.

Leave a comment

You must be logged in to post a comment.