Birds-Eye.Net
All things broadband and more...
 
Web Birds-Eye.Net

What's New?

Ruby on Rails (RoR)
Programming Reference


Models
External database connections
Passing current_user into model
Passing object into model
Using static lookup tables
Validates IF
Validates MongoMapper

Views
Dynamically delete form element
Edit create nested data
HTML form field check_box
Layout jQuery datatable module
Select array
Select cascading via JS
Text_area Array
Text_area listing submit
Text field format time

Controllers
Dynamic model selection
Including first item from a sorted desc table
Using from_unixtime on epoch dates
Custom SQL Query Examples

Rack
Integrated NTLM/Kerberos Authentication
Pass-through Authentication w/ NTLM

ActionMailer
Broken links in emails

Rails General
Add, Subtract, Multiply, and Divide
Calculate number of weekdays for date range
Date->Epoch & Epoch->Date
Calculate past/present payroll dates
Extract first letter of each word
Hash of hashes assignment
Using: variable as hash index

jQuery
jQuery accordion MongoDB

Rails Framework Examples

Apotomo Widget Using Erb

MySQL
Converting Julian Dates to Epoch

d3 Charting
Configuration to Work with Rails Apps
A simple bar chart example

Other
Setup VPN on iMac
SSH Key Generation

More to come

 

Rails Arithmetic: Add, Subtract, Multiply, and Divide

By: Bruce Bahlmann - Contributing Author (your feedback is important to us!)

In rails development, you will often want to use basic arithmetic. While all these work as you would expect, rails doesn't handle results well - particularly those results which do not come in the form of a whole number. So, this post is all about handling rails results that come of the form of a fraction or what rails call them (floats).

Below, we break down various mathematical operations (add, subtract, multiply, and divide) and how to achieve the kind of results you want without having to hunt-n-peck your way through various incomplete rails posts to find what you are looking for:

Addition:

[Addition]

1 + 2
=> 3

1 + 2.0
=> 3.0

(1 + 2.0).round(0)
=> 3

x = nil
=> nil

x + 1
=> noMethodError: undefined method '+' for nil:NilClass

x = x + 1
=> noMethodError: undefined method '+' for nil:NilClass

x =+ 1
=> 1
[This is the same as saying: x = 1, rails ignores the plus (+) sign]


[The correct way to increment a variable]
x += 5
=> 15

Clearly simple addition of integers produces an integer and similarly addition which includes a float will produce a float. The key with addition is to account for the possibility of encountering a nil value. Note that rails does not have a formal increment counter (e.g. ++) like some other languages. The best way to increment or handle cases where you doing simple addition to a variable is to use += assignments rather than straight up addition using the plus (+) sign.

NOTE that =+ is also a valid ruby operator, only it DOES NOT ADD the number to the variable as one might expect. Rather it simply assigns the variable what ever number you have to the right.

Subtraction:

[Subtraction]

16 - 9
=> 7

9.0 - 16
=> -7.0

(2.0 - 1).round(0)
=> 1

x = nil
=> nil

x - 9
=> noMethodError: undefined method '-' for nil:NilClass

x = x - 9
=> noMethodError: undefined method '-' for nil:NilClass

x =- 9
=> -9
[This is the same as saying: x = -9, rails uses the minus (-) sign to interpret the number]


[The correct way to decrement a variable]
x -= 5
=> 2

Similar to addition, rails does not have a decrement function (e.g. --) and there is an issue when dealing with nil values. So to be safe, you should the assignment operator =- to perform decrements as well as assignments involving subtraction where possible.

NOTE that =- is also a valid ruby operator, only it DOES NOT SUBTRACT the number from the variable as one might expect. Rather it simply assigns the variable what ever number you have to the right and uses the minus (-) to take the negative of the number to the right. 

Multiplication:

[multiplication]

5 * 66
=> 330

6.0 * 55
=> 330.0

(6.0 * 55).round(0)
=> 330

x = nil
=> nil

x * 9
=> noMethodError: undefined method '*' for nil:NilClass

Unlike addition and subtraction, there is no assignment operator for multiplication (e.g. =*). When multiplying a variable that could be nil with some other number, you need to first test that variable for nil, and only proceed with using it in the calculation if the tested variable is not nil.

Division:

[Division]

4/2
=> 2

1/2
=> 0

7/3
=> 2

Float(1)/2
=> 0.5

Float(7)/3
=> 2.33333333333333

(Float(7)/3).round(2) 
=> 2.33

3.6/1.2
=> 3

3.8/0.7
=> 5.42857142857143

(3.8/0.7).round(4) 
=> 5.4286

RECOMMENDED METHOD:
(Float x/y)
=> result that always observes fraction

Notice above, that when using a whole number as the dividend (top number) and the divisor (bottom number) the results will be truncated as if rails thought it were only working with integers (whole numbers). To resolve this, you need to declare the dividend as a Float (see above and remember to capitalize) - but only if dividend and divisor are whole numbers. Note that if either the dividend or the divisor is a real number (Float), rails properly states the results as a fraction (if any). To be safe, it is probably best to declare the dividend as a Float to ensure rails properly produces a fraction when it is supposed to.

Common errors when working with numbers:

Rails does not like it when you mix text with arithmetic, so to help you be more explicit, you need to use rails the rails hander #{} within double quotes ("). In this way, within the curly brackets, you can use the arithmetic and then mix in custom text outside of the curly brackets, but still within the double quotes (").

[can't convert Fixnum into String]

@survey["delta"] = (@survey.inviteListing.size - @survey.completedListing.size) +" is the difference"
=> "can't convert Fixnum into String"

USE Instead:
@survey["delta"] = "#{(@survey.inviteListing.size - @survey.completedListing.size)}" +" is the difference"

Can Birds-Eye.Net help you or your Company?
Receive your Birds-Eye.Net articles and white papers hot off the presses by adding our RSS feed to your reader.

 

(C) Copyright Birds-Eye.Net, All rights reserved.
It is against the law to reproduce this content or any portion of it in any form without the explicit written permission of Birds-Eye Network Services, LLC. Federal copyright law (17 USC 504) makes it illegal, punishable with fines up to $100,000 per violation plus attorney's fees.