Numbers in Ruby
Let's play with Numbers. In Ruby, numbers without decimal points are called integers, and numbers with decimal points are usually called floating-point numbers or, more simply, floats (you must place at least one digit before the decimal point). Here's the program p002rubynumbers.rb
=begin Ruby Numbers Usual operators: + addition - subtraction * multiplication / division =end
puts 1 + 2 puts 2 * 3 # Integer division # When you do arithmetic with integers, you'll get integer answers puts 3 / 2 puts 10 - 11 puts 1.5 / 2.6 |
Ruby integers are objects of class Fixnum or Bignum. The floating-point numbers are objects of class Float, corresponding to the native architecture's double data type. |
The class hierarchy is as shown in this figure:

The above figure courtesy Donald Craig.
Operators and Precedence Let us look at Ruby's operators. They are arranged here in order from highest to lowest precedence.
| :: | Scope |
| [] | Indexing |
| ** | Exponentiation |
+ - ! ~
| Unary pos/neg, not,...
|
* / %
| Multiplication, Division...
|
+ -
| Addition, subtraction...
|
<< >>
| Logical shifts,...
|
| & | Bitwise and
|
| ^
| Bitwise or, xor
|
> >= < <=
| Comparison |
== === <=> != =~ !~
| Equality, inequality...
|
| && | Boolean and
|
| || | Boolean or
|
.. ...
| Range operators
|
= (also +=, -=,...)
| Assignment |
| ?: | Ternary decision
|
| not | Boolean negation
|
and, or
| Boolean and, or
|
The above table is from Hal Fulton's book - The Ruby Way.
Assignment: Write a Ruby program that tells you how many minutes are there in a year (do not bother right now about leap years etc.).
Suggestions:
- Read online Chris Pine's Learn to Program book
- Read Matz's The Philosophy of Ruby
- Hear Geoff Grosenbach's Ruby Basics
- Check out Web based Learning for better coding and design