Re: ruby equivalent PHP function is_numeric?

From: [email protected] [mailto:[email protected]] On

It really is too bad that String.to_f does not throw an exception - or
at least return NaN - when the string is not a number.

Float( mystring )
does raise an exception, however.

On 11/17/06, Gavin K. [email protected] wrote:

From: [email protected] [mailto:[email protected]] On

It really is too bad that String.to_f does not throw an exception - or
at least return NaN - when the string is not a number.

Float( mystring )
does raise an exception, however.

hmm, I’m new to Ruby too, so I tried this in irb.

irb(main):001:0> muppet = “3.14”
=> “3.14”
irb(main):002:0> muppet.to_f
=> 3.14
irb(main):003:0> muppet
=> “3.14”
irb(main):004:0> penguin = “banana”
=> “banana”
irb(main):005:0> penguin.to_f
=> 0.0
irb(main):006:0> Float(muppet)
=> 3.14
irb(main):007:0> Float(penguin)
ArgumentError: invalid value for Float(): “banana”
from (irb):7:in `Float’
from (irb):7
from :0
irb(main):008:0> exit

I think String#to_f should probably throw an exception too. actually,
I think whatever the behavior of the two methods is, it should
probably be the same in either case. otherwise you end up with the
kind of API where you have thirty different methods of doing the same
thing, but only two of them work, and of the two that work, neither of
them work all the time.

it’s like, you have Perl’s “more than one way to do it” and Python’s
“only one way to do it” and you have to be careful about letting these
creatures mate, it’s kind of a mad scientist situation, you could end
up with a monster like, “there’s more than one way to do it, but only
one of them actually works, and which one it is varies unpredictably.”

On Sat, Nov 18, 2006 at 04:31:14AM +0900, Giles B. wrote:

irb(main):001:0> muppet = “3.14”
=> 3.14
kind of API where you have thirty different methods of doing the same
thing, but only two of them work, and of the two that work, neither of
them work all the time.

it’s like, you have Perl’s “more than one way to do it” and Python’s
“only one way to do it” and you have to be careful about letting these
creatures mate, it’s kind of a mad scientist situation, you could end
up with a monster like, “there’s more than one way to do it, but only
one of them actually works, and which one it is varies unpredictably.”

Nah. Integer( ) works the same way. Think about Float( ) and Integer( )
vs. to_i and to_f being sort of like #to_int vs. #to_i. to_i is like, I
want an int out of this, whether this string is an int or not. Integer
is like “I have an integer, it just happens to be current represented as
a string.”

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs