[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

FEATURE SUGGESTION: Accept default value for to_f and to_i

Mr Magpie

11/27/2007 2:15:00 AM

I suggest that to_i() and to_f() have an optional parameter added with
the default value of 0 (for backwards compatibility).

This would allow code like

if astring.to_f(nil)
# valid, so use it
else
# not a valid float, nil was returned, so handle error
end

Currently, from the output of these functions, a conversion error is
indistiguishable from a valid input of 0.

It would allow even more succinct code when, say, reading in a
configuration value :
delay = configuration['delay'].to_f(DEFAULT_DELAY)

I find this pattern of providing a default that is returned in the event
of an error (instead of throwing an exception or returning nil or 0)
allows for simple, safe and succinct code.

Another example is xpath_value(aRootNode,aXPath,aDefault=nil) which
returns aDefault if there is any problem returning the value selected by
aXPath (it often doesn't matter what the problem is).
--
Posted via http://www.ruby-....

1 Answer

Trans

11/27/2007 2:02:00 PM

0



On Nov 26, 9:15 pm, Mr Magpie <gazmcghees...@yahoo.com.au> wrote:
> I suggest that to_i() and to_f() have an optional parameter added with
> the default value of 0 (for backwards compatibility).
>
> This would allow code like
>
> if astring.to_f(nil)
> # valid, so use it
> else
> # not a valid float, nil was returned, so handle error
> end

if (num = astring.to_f) == 0
# may or may not be valid
begin
num = Float(astring)
rescue
# not a valid float, nil was returned, so handle error
end
end

# valid num, so use it

You can wrap it in a "monkey patch" if you like.

T.