Jonathan Gnagy's Blog

Rails for everyone!

Ruby and Numbers

Sometimes you need to work with numbers in Ruby. We all do it, and its necessary. But sometimes you run across a situation where you need to take a string that looks like a number, and convert it to a number. For instance, let say we’ve got the following:


number = "3"

Now lets say that I want to use this in some math… It won’t work very well:


wrong_answer = number * 14 # => TypeError: String can't be coerced into Fixnum

So, how can we make this work? Take a look at this:


answer = Integer(number) * 14 # => 42

This isn’t the only method that provides this kind of functionality. Need to work with Floats? Try this:

1
2
number = "3.14"
answer = Float(number) * (4**2) # => 50.24

Just thought I’d share some useful Ruby code. I haven’t posted code in a while, and I figured it might help somebody out there.

Comments:
Add a comment:
Please leave following field blank:
SubmitSubmit    HelpHelp