Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type Conversions in Ruby: The "Right" Way?

Tags:

types

ruby

I am trying to decide if a string is a number in Ruby. This is my code

whatAmI = "32.3a22"
puts "This is always false " + String(whatAmI.is_a?(Fixnum));
isNum = false;
begin
  Float(whatAmI)
  isNum = true;
rescue Exception => e
  puts "What does Ruby say? " + e
  isNum = false;
end
puts isNum

I realize that I can do it with a RegEx, but is there any standard way to do it that I'm missing? I've seen a can_convert? method, but I don't seem to have it.

Is there a way to add a can_convert? method to all Strings? I understand that it's possible in Ruby. I also understand that this may be totally unecessary...

Edit The to_f methods do not work, as they never throw an Exception but rather just return 0 if it doesn't work out.

like image 620
Dan Rosenstark Avatar asked Jan 27 '09 13:01

Dan Rosenstark


2 Answers

You've got the right idea. It can be done a little more compactly, though:

isNum = Float(whatAmI) rescue nil

Inlining "rescue" is great fun. Parenthesize the part you're rescuing if you put it in the middle of more stuff, like:

if (isNum = Float(whatAmI) rescue nil) && isNum > 20
  ...
like image 122
glenn mcdonald Avatar answered Sep 21 '22 09:09

glenn mcdonald


This might sound overly critical, but based on your description, you're almost certainly doing something "wrong"... Why would you need to check whether a String is a valid representation of a Float but not actually convert the String?

This is just a hunch, but it may be useful to describe what you're trying to accomplish. There's probably a "better" way.

For example, you might want to insert the String into a database and put together an sql statement using string concatenation. It would be preferable to convert to a Float and use prepared statements.

If you just need to inspect the "shape" of the string, it would be preferable to use a regular expression, because, as dylan pointed out, a Float can be represented in any number of ways that may or may not be appropriate.

You may also have to deal with international input, in Europe, a comma is used instead of a period as decimal seperator, yet Ruby Floats have to use the (.).

like image 23
a2800276 Avatar answered Sep 21 '22 09:09

a2800276