Ruby interpreted variables is_a? -


i looking check variabe type based on value held in variable struggling it. i'm new ruby can tell me how have value of variable interpreted in expression? current code looks like:-

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

where variable contain , variable_type contains type of variable string or fixnum. code gives me typeerror: class or module required. thoughts?

your code sends string object #is_a? method , #is_a method expects class.

for example, string vs. "string":

variable = "hello!" variable_type = string "#{variable_type}" # => "string"  # code: if variable.is_a?("#{variable_type}")     puts variable end 

#is_a? expects actual class (string, fixnum, etc') - can see in the documentation #is_a?.

you can adjust code in 2 ways:

  1. pass class, without string.

  2. convert string class using module.const_get.

here example:

variable = "hello!" variable_type = string "#{variable_type}" # => "string"  # passing actual class: if variable.is_a?(variable_type)     puts variable end  # or,  # converting string type: if variable.is_a?( module.const_get( variable_type.to_s ) )     puts variable end 

Comments

Popular posts from this blog

c++ - Difference between pre and post decrement in recursive function argument -

php - Nothing but 'run(); ' when browsing to my local project, how do I fix this? -

php - How can I echo out this array? -