Intro to Ruby - Numbers

Ruby

Overview

Yesterday we learned about strings and today it is about numbers. The following is a breakdown of some of the basic things you can do with numbers.

NOTE: In order to output the various numbers to the console, the “to_s” (i.e. to string) method was used to concatenate the number with the string prefix. In some cases, parenthesis were used to achieve the desired output. Methods will explained more in future posts.

Code

# A simple fixnum.
puts "01 Fixnum: " + 1.to_s

# A simple decimal.
puts "02 Decimal: " + 2.5.to_s

# A more complicated decimal using scientific notation.
puts "03 Scientific Decimal Notation: " + 3.0e5.to_s

# A big number for very large numbers outside the range of a fix number.
puts "04 Bignum: " + 1234567890123.to_s

# A floated number at the maximum value.
puts "05 Float (Maximum): " + Float::MAX.to_s

# Another example of methods on a number chained with the to_s method.
# In this case we are asking if the number is zero or not (a boolean is returned).
puts "06 Method Example: " + 4.zero?.to_s

# Addition (using parenthesis to compute the value first and then calling the to_s method on the result).
puts "07 Addition: " + (2 + 3).to_s

# Subtraction (using parenthesis to compute the value first and then calling the to_s method on the result).
puts "08 Subtraction: " + (5 - 2).to_s

# Multiplication (using parenthesis to compute the value first and then calling the to_s method on the result).
puts "09 Multiplication: " + (7 * 2).to_s

# Division (using parenthesis to compute the value first and then calling the to_s method on the result).
puts "10 Division: " + (12 / 2).to_s

# A hex (base-16) number is prefixed with a 0x notation.
puts "11 Hex: " + 0x2F1.to_s

# A octal (base-8) number is prefixed with a 0 notation.
puts "12 Octal: " + 0252.to_s

# Underscores can be used to make numbers more readable. The result removes the underscores.
puts "13 Readability: " + 2009_02_11.to_s

Output

01 Fixnum: 1
02 Decimal: 2.5
03 Scientific Decimal Notation: 300000.0
04 Bignum: 1234567890123
05 Float (Maximum): 1.79769313486232e+308
06 Method Example: false
07 Addition: 5
08 Subtraction: 3
09 Multiplication: 14
10 Division: 6
11 Hex: 753
12 Octal: 170
13 Readability: 20090211

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 02-numbers.rb.

What’s Next

Ranges.

Tags:

Thursday, February 19th, 2009 Software

No comments yet.

Leave a comment

You must be logged in to post a comment.