Thursday, February 4, 2010

Section 5.5. Inquiring About Numbers


Math > Inquiring About Numbers




5.5. Inquiring About Numbers


At times you need to find out things about a number or variable. Is it an integer? A zero? A number at all? Ruby's math methods can handle that. These methods come from all kinds of classes.


Let's start things out simple. Let's ask if a value is a zero or not.

op = 0
op.zero? # => true
op.nonzero? # => false


That was a little too obvious. (But that's what I like about Ruby.) Try something more meaningful:

op = 0

if !op.zero? # not a zero?
puts 12 / op
else
puts "Can't divide by zero."
end

op = 2

if op.nonzero? # is it nonzero?
puts 12 / op
else
puts "Can't divide by zero."
end


Both if statements mean essentially the same thing: divide 12 by op if it isn't a zero.


The integer? method comes from the Numeric class:

12.integer? # => true
12.0.integer? # => false
-1.integer? # => true
-12.integer? # => true


This method needs a little more meaning in its life.

num = 4 # => 4

if num.integer?
puts "Invited guests: " + num.to_s
else
puts "Only whole persons can come to this party."
end


Check whether a number is finite or infinite with the finite? and infinite? Float methods (in fact, these methods only work for floats):

0.0.finite? # => true
(-1.0/0.0).finite? # => false
(+1.0/0.0).finite? # => false

0.0.infinite? # => nil
(-1.0/0.0).infinite? # => -1
(+1.0/0.0).infinite? # => 1


Check whether a floating-point value is a number at all with Float's nan?:

val = 1.0
val.nan? # => false
val = 0.0/0.0
val.inspect # => "NaN"
val.nan? # => true


5.5.1. Iterating Through Blocks


Starting with zero, the times method iterates value times. Here, value is 10:

10.times { |i| print i, " " } # => 0 1 2 3 4 5 6 7 8 9


You also get the ability to do something like this:

10.times { |i| print 5*i, " " } # => 0 5 10 15 20 25 30 35 40 45


You can rewrite the block this way:

10.times do |i|
puts 5*i
end


or this way:

10.times do |i| print 5*i, " " end


The block can be opened and closed with do/end or {and }. The braces are a little more concise and more common.


Integer also has the downto and upto methods, which were already demonstrated and compared to the for loop in Chapter 3, but I'll show them again here for a brief refresher. First, the downto method:

100.downto(1) { |c| print c, " "; sleep 1 }


This method prints out the numbers from 100 down to 1, sleeping for 1 second before each number is printed. The upto method goes the other direction:

1.upto(100) { |c| print c, " "; sleep 1 }


 

 


No comments: