简体   繁体   中英

How do I inspect the class type of attributes in ruby?

How do I create a method like:

def process_by_type *things

  things.each {|thing|
    case thing.type
      when String

      when Array

      when Hash

      end

    end
  }
end

I know I can use kind_of?(Array), etc. But I think this would be cleaner, and I cant' find a method for it on the Class:Object documentation page.

Try .class :

>> a = "12"
=> "12"
>> a.class
=> String
>> b = 42
=> 42
>> b.class
=> Fixnum

Using the form of case statement like what you're doing:

case obj
  when expr1
    # do something
  when expr2
    # do something else
end

is equivalent to performing a bunch of if expr === obj (triple-equals comparison). When expr is a class type, then the === comparison returns true if obj is a type of expr or a subclasses of expr .

So, the following should do what you expect:

def process_by_type *things

  things.each {|thing|
    case thing
      when String
        puts "#{thing} is a string"
      when Array
        puts "#{thing} is an array"
      when Hash
        puts "#{thing} is a hash"
      else
        puts "#{thing} is something else"
    end
  }
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM