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
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.
This is not the "correct answer", I would simply like to point out that you should not use type in python you should use isinstance instead
isinstance(input, list) # test for list
isinstance(inpit, [float, int]) # test for number
if you are using python 3 you can check for abstract base classes
import collections
isinstance(input, collections.abs.Sequence) # sequence = tuple, list and a lot of other stuff that behaves that way
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With