Wednesday, September 30, 2009

Ruby on Rails : Numeric : Integer / Float

Number Basics

One type of class in the ruby programming language is numbers. Actually, there are two types of numbers; integers and floating points. Integers are the default number. If you remember back to math class, integers cannot have decimal places. Likewise, in floating points, you can have a decimal point. Another important point is that numbers are eventually converted to a string, but after almost everything else is executed. Therefore, numbers and strings cannot do things together like concatenate.

Converting Between Different Classes


Often you will want to convert one type of object to another so you can make it interact with objects of that class. Luckily, ruby makes it really easy:

Convert to String:
<%= '5'.to_s %>
Convert to Integer:
<%= '5'.to_i %>
Convert to Floating Point:
<%= '5/3'.to_f %>

Methods

Integers are the default numbers used in the ruby language. Use them if you are not going to have to deal with a decimal point. For example, integers are good for counting by ones. If you perform a calculation in ruby as an integer, and it has a decimal point it will essentially be chopped off. When you convert a number to a floating point, you gain additional methods to apply to it. The most important ones are how to manipulate the number when rounding.

MethodCode Description
Integer<%= 7/4 %>Result: 1
Float<%= 7/4.to_f %>Result: 1.75
Rounding<%= (5/3.to_f).round %>If 2.3 will be 2 and 2.55 will be 3. In this case, the result would be 2.
Ceil<%= (5/3.to_f).ceil %>If it's 1.2 it will be 2 and if it's 1.6 it will still be 2. In this case the result would be 2.
Floor<%= (5/3.to_f).floor %>It is just cutting the decimal point off and/or like what would happen in a normal integer. In this case, the result would be 1.
Remainder<%= 7.remainder(4) %>Result: 3

Taken From : http://net.tutsplus.com/videos/screencasts/ruby-on-rails-week-4/
Library Class :
http://corelib.rubyonrails.org/classes/Numeric.html
http://corelib.rubyonrails.org/classes/Bignum.html#M000993

1 comment:

  1. This is my first opportunity to visit this website. I found some interesting things and I will apply to the development of my blog. Thanks for sharing useful information. Ruby on Rails Developers

    ReplyDelete