yveskas yveskas - 4 years ago 175
Ruby Question

Checking variable type in Ruby

I have an issue checking variable types in ruby. Here is a sample code of python that I would like to replicate in ruby. I would like to check the

input
type: whether string, int, or list, and proceed to a specific printing action.

def printing (input):
if type(input) == type(""):
pass
elif type(input) == type(1):
pass
elif type(input) == type([]):
pass
elif type(input) == type({}):
pass
elif type(input) == type(()):
pass


I cannot find a method that will do this in ruby. The code below is what I want it to look like. I am assuming that I have to check the type at the case stage.

def printing (element)
case element
when element.type("")
puts element
when element.type(2)
puts element
when element.type({})
element.each_pair { |name, val| print "#{name} : #{value}"}
when element.type([])
element.each {|x| print x}
end
end

Answer Source

I think you are looking for Object#class. Here:

element = {}
element.class
# => Hash
a = []
a.class
# => Array

This will make your switch case as follows:

case element
when String
 # do something
when Fixnum
 # do something
when Hash
 # do something
when Array
 # do something
end

Note: As mentioned by @ndn in comments below, case statement should not have .class in it (which I had initially in my answer). You can find the explanation here.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download