Information Technology Reference
In-Depth Information
Mathematical Operations
Ruby exposes basic arithmetic operations such as addition, multiplication, and division as a
core feature of the language:
1 + 2
#=> 3
3 * 4
#=> 12
5 / 6 . 0
#=> 0.8333...
Let's say that to ensure a productive and collaborative work environment, your company
policy requires that your team take a bacon break every three hours, on the hour. Even
though the policy is strict, the team often becomes engrossed in its work and forgets to check
the clock. You could write a short Ruby script that alerts the team when it should stop and
enjoy some freshly-cooked bacon:
# Bacon time is every third hour
iif hour % 3 == 0
puts "It's BACON time!"
end
end
More complex operations, such as rounding or polynomial distributions, are exposed in
Ruby's Math module. You can use the Math.hypot method in a Ruby script to calculate the
length of a diagonal for a right triangle by returning the sum of the squares of its two sides:
Math . hypot ( 43 , 57 ) #=> 71.40028011149536
Additional functions and constants such as log , sin , sqrt , e , and π are also contained in the
Math module.
Strings
There are two common ways to create strings in Ruby: with single quotes and with double
quotes. Single-quoted strings have the advantage of one fewer keystroke and do not apply in-
terpolation .
Double-quoted strings are useful when variables need to be evaluated as part of the string
content—this evaluation process is known as string interpolation . A hash symbol is used as a
placeholder within a double-quoted string to indicate to Ruby that the placeholder should be
Search WWH ::




Custom Search