Technology Agnostic Rubyist : Open Source Lights The Way

Friday, November 14, 2008

Dirty numbers

/$#@!

This is a pretty basic programming concept but I haven't touched this blog in a while here we go...

Say you're working with numbers in a database field. Those numbers were keyed in by people using a different system, and the other system somehow stored non-numeric values in a numeric field.

Since Ruby does not have strong typing, an easy way to check and see if a field is an integer is to compare its integer value with its actual value.

if (somefield.to_i == somefield)

For example:
n = 1234567
if (n.to_i==n) => true

If the value of n is not keyed properly the equality test returns false
n = "12345x67"
if (n.to_i=="12345x67") => false

Easy!

No comments:

Tweets

Contributors