Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking variable type in Ruby

Tags:

python

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
like image 639
yveskas Avatar asked Mar 02 '26 02:03

yveskas


2 Answers

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.

like image 87
shivam Avatar answered Mar 03 '26 17:03

shivam


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
like image 20
jcr Avatar answered Mar 03 '26 16:03

jcr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!