Jj No
Jj No

Reputation: 61

Ruby interpreted variables is_a?

I am looking to check a variabe for its type based on the value held in another variable but am struggling with it. I'm completely new to ruby but can anyone tell me how to have the value of a variable interpreted in the expression? My current code looks like:-

if variable.is_a?("#{variable_type}")
    puts variable
end

Where variable could contain anything and variable_type contains the type of a variable like String or Fixnum. But currently this code gives me TypeError: Class or module required. Any thoughts?

Upvotes: 0

Views: 948

Answers (3)

Myst
Myst

Reputation: 19221

Your code sends a String object to the #is_a? method and the #is_a method expects a Class.

For example, String vs. "String":

variable = "Hello!"
variable_type = String
"#{variable_type}" # => "String"

# your code:
if variable.is_a?("#{variable_type}")
    puts variable
end

#is_a? expects the actual Class (String, Fixnum, etc') - as you can see in the documentation for #is_a?.

You can adjust your code in two ways:

  1. pass the Class, without the string.

  2. convert the string to the class using Module.const_get.

here is an example:

variable = "Hello!"
variable_type = String
"#{variable_type}" # => "String"

# passing the actual class:
if variable.is_a?(variable_type)
    puts variable
end

# or,

# converting the string to a the type:
if variable.is_a?( Module.const_get( variable_type.to_s ) )
    puts variable
end

Upvotes: 2

Andrey Deineko
Andrey Deineko

Reputation: 52357

TypeError: Class or module required

It means, that to use is_a? varibale_type should hold a class name (any).

Therefore if you hold anything else except for class name in variable_type it will give you this error.

a = :a

variable_type = Symbol
a if a.is_a? variable_type
# => :a

If variable type is a string, you will have to use Module#const_get:

variable_type = 'Symbol'
a if a.is_a? Object.const_get(variable_type)
# => :a

Upvotes: 1

spickermann
spickermann

Reputation: 106972

Just a little example:

variable = 1

variable_type = String
puts variable if variable.is_a?(variable_type)
#=> nil

variable_type = Integer
puts variable if variable.is_a?(variable_type)
#=> 1

Or when your variable_type is a string:

variable_type = 'Integer'
puts variable if variable.is_a?(Object.const_get(variable_type))
#=> 1

Upvotes: 2

Related Questions