[#964] Bastion or SecurityManager for Ruby? — Clemens Hintze <clemens.hintze@...>

Hi,

15 messages 1999/12/10

[#989] a question about to_i — Friedrich Dominicus <Friedrich.Dominicus@...>

Sorry, I'm quite new to ruby. But I encounterd the following problem. If

17 messages 1999/12/19

[ruby-talk:00992] Re: a question about to_i

From: gotoken@... (GOTO Kentaro)
Date: 1999-12-19 08:56:03 UTC
List: ruby-talk #992
Hi, 

In message "[ruby-talk:00989] a question about to_i"
    on 99/12/19, Friedrich Dominicus <Friedrich.Dominicus@inka.de> writes:

>I have a string "bla" and apply to_i to it I get 0. This seems to be
>quite strange because it is what it is a string so shouldn't an
>exeception be rissen or s.th simular. 

to_i or to_f return *always* a number. Those work as a kind of type
conversion.

>And how do you check if a string is a number then?

The following shows a dirty but simple way:

  $SAFE = 1  # to suppress applying "eval" to a tainted string. 
  class String
    def numeric?(klass = Numeric)
      unless klass <= Numeric
        raise ArgumentError, "non Numeric type `#{klass}'"
      end
      begin
        res = eval self
        if res.is_a? klass then res else false end
      rescue NameError
        false
      end
    end
  end

  p "12345".numeric?          #=> 1234
  p "0xfff".numeric?          #=> 4095
  p "-1.23".numeric?          #=> -1.23
  p "1.2e1".numeric?          #=> 12.0
  p "1.2e1".numeric?(Float)   #=> 12.0
  p "1.2e1".numeric?(Integer) #=> false
  p "hack!".numeric?          #=> false

Hope this helps.

-- gotoken

In This Thread