Does ruby 1.9.2 have an is_a? function?

前端 未结 6 1069
忘掉有多难
忘掉有多难 2020-12-17 06:59

I googled that there is an is_a? function to check whether an object is an integer or not.

But I tried in rails console, and it doesn\'t work.

I

相关标签:
6条回答
  • 2020-12-17 07:25

    You forgot to include the class you were testing against:

    "1".is_a?(Integer) # false
    1.is_a?(Integer) # true
    
    0 讨论(0)
  • 2020-12-17 07:27

    I wanted something similar, but none of these did it for me, but this one does - use "class":

    a = 11
    a.class
    => Fixnum
    
    0 讨论(0)
  • 2020-12-17 07:32

    i used a regular expression

    if a =~ /\d+/
       puts "y"
    else
       p 'w'
    end
    
    0 讨论(0)
  • 2020-12-17 07:32

    Maybe this will help you

    str = "1"
    => "1"
    num = str.to_i
    => 1
    num.is_a?(Integer)
    => true
    
    str1 = 'Hello'
    => "Hello"
    num1 = str1.to_i
    => 0
    num1.is_a?(Integer)
    => true
    
    0 讨论(0)
  • 2020-12-17 07:41

    There's not a built in function to say if a string is effectively an integer, but you can easily make your own:

    class String
      def int
        Integer(self) rescue nil
      end
    end
    

    This works because the Kernel method Integer() throws an error if the string can't be converted to an integer, and the inline rescue nil turns that error into a nil.

    Integer("1") -> 1
    Integer("1x") -> nil
    Integer("x") -> nil
    

    and thus:

    "1".int -> 1 (which in boolean terms is `true`)
    "1x".int -> nil
    "x".int -> nil
    

    You could alter the function to return true in the true cases, instead of the integer itself, but if you're testing the string to see if it's an integer, chances are you want to use that integer for something! I very commonly do stuff like this:

    if i = str.int
      # do stuff with the integer i
    else
      # error handling for non-integer strings
    end
    

    Although if the assignment in a test position offends you, you can always do it like this:

    i = str.int
    if i
      # do stuff with the integer i
    else
      # error handling for non-integer strings
    end
    

    Either way, this method only does the conversion once, which if you have to do a lot of these, may be a significant speed advantage.

    [Changed function name from int? to int to avoid implying it should return just true/false.]

    0 讨论(0)
  • 2020-12-17 07:46

    Ruby has a function called respond_to? that can be used to seeing if a particular class or object has a method with a certain name. The syntax is something like

    User.respond_to?('name') # returns true is method name exists
    otherwise false
    

    http://www.prateekdayal.net/2007/10/16/rubys-responds_to-for-checking-if-a-method-exists/

    0 讨论(0)
提交回复
热议问题