a strict version of to_f ?

R

Ryo

Hello all,

I'm wondering if there's a strict version of to_f,
such as

"1.3".strict_to_f # -> 1.3
"hello".strict_to_f # raises an exception

One could implement it as

def String.strict_to_f
if self =~ regex_floating_point
return self.to_f
else
raise some_exception
end
end

But, 1) it's not trivial (to me) to construct a correct
regex_floating_point and 2) somebody may already have done
this (that is, I don't want to reinvent the wheel).

I'm my applications, raising an exception to

"hello".to_f

is *always* better than returning 0.0 .

Cheers,
Ryo
 
T

ts

R> "1.3".strict_to_f # -> 1.3
R> "hello".strict_to_f # raises an exception

#Float

moulon% ruby -e 'Float("hello")'
-e:1:in `Float': invalid value for Float(): "hello" (ArgumentError)
from -e:1
moulon%
 
M

Marcin Mielżyński

Ryo said:
Hello all,

I'm wondering if there's a strict version of to_f,
such as

class String
def strict_to_f
Float(self)
end
end

lopex
 
R

Ryo

Thank you all who responded!

Tim said:
Try Float()

irb(main):001:0> Float("1.3")
=> 1.3
irb(main):002:0> Float("hello")
ArgumentError: invalid value for Float(): "hello"
from (irb):2:in `Float'
from (irb):2

Ah, is this a change introduced in Ruby 1.8 ?
In fact, I knew Float, but the old pickaxe book says

Float Float( arg ) -> aFloat
Returns arg converted to a float. Numeric types are converted
directly, nil is converted to 0.0, and the rest are converted
using arg.to_f.

Anyway, my problem is solved.

Cheers,
Ryo
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,206
Messages
2,571,069
Members
47,675
Latest member
RollandKna

Latest Threads

Top