On Fri, Dec 28, 2012 at 5:41 AM, Damián M. González
<[email protected]> wrote:
>> In these cases, I just double convert i.e.
>>
>> irb(main):016:0> buffer = 'fred'
>> => "fred"
>> irb(main):017:0> buffer.to_i.to_s == buffer
>> => false
>
> Have to say that that's very cleaver. Very good solution.
Sorry to disagree. There are more clever solutions:
Use an Integer and deal with the exception.
1. immediately
irb(main):001:0> buffer = 'fred'
=> "fred"
irb(main):002:0> i = Integer(buffer)
ArgumentError: invalid value for Integer(): "fred"
from (irb):2:in `Integer'
from (irb):2
from /usr/bin/irb:12:in `<main>'
irb(main):003:0> begin; i = Integer(buffer); puts "int"; rescue
ArgumentError; puts "no int"; end
no int
=> nil
2. by converting the value to nil if it is not a number
irb(main):004:0> j = Integer(buffer) rescue nil
=> nil
irb(main):005:0> if j; puts "int"; else puts "no int"; end
no int
=> nil
Kind regards
robert
--
remember.guy do |as, often| as.you_can - without end
http://blog.rubybestpractices.com/
-- You received this message because you are subscribed to the Google Groups
ruby-talk-google group. To post to this group, send email to
[email protected]. To unsubscribe from this group, send email
to [email protected]. For more options, visit this
group at https://groups.google.com/d/forum/ruby-talk-google?hl=en