{

How to check the type of a variable is Ruby| Ruby on Rails By Example


Sometimes, We want to check a variable type. Type can be an int or any object.

Variable can be number, float, boolean, array, or hash.

How to check variable type in Ruby

Ruby provides a class property, that returns the class of a variable.

Each variable has this property It is always called with variable.

Here is a syntax:

variable_name.class

Here is a complete example

employees = {'frank' => 5000, 'Andrew' => 6000, 'Rocky' => 10000}
array=[1,2,3,4,5];
puts 1.class
puts 1.0.class
puts  'str'.class
puts false.class
puts true.class
puts employees.class
puts array.class
puts nil.class

Output:

Integer
Float
String
FalseClass
TrueClass
Hash
Array
NilClass

In the above example, the class returns the following things.

  • normal number returns Integer Class
  • floating numbers return Float Class
  • a collection of characters enclosed in quotes returns String Class
  • Boolean values returns FalseClass or TrueClass Class
  • Objects return Hash Class
  • Array variable returns Array Class
  • Nil value returns NilClass

How to check given variable is an array or Hash?

variable class property returns the class.

Use this class in an if conditional statement to return true or false. We can check given variable is an array or not in many ways. There are multiple ways we can check with array properties and methods.

To check if a variable is an array in ruby.

array=[1,2,3,4,5];
puts array.class
if (array.class == Array)
 puts "Variable is an array\n"
else
 puts "Variable is not an array\n"
end

Output:

Variable is an array

To check if the given variable is a Hash or not.

employees = {'frank' => 5000, 'Andrew' => 6000, 'Rocky' => 10000}
if (employees.class == Hash)
 puts "Variable is an Hash\n"
else
 puts "Variable is not an Hash\n"
end

Output:

Variable is a Hash

Conclusion

Ruby provides a property class on a defined variable which returns the datatype of a variable.

Also, You can check if a variable is a hash or array.

THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.





Related posts

How to Convert current Unix timestamp epoch to DateTime in Ruby Programming| Ruby on Rails by Example

How to remove an element from an array in Ruby Programming| Ruby on Rails by Example

How to print the name of a Ruby class| Ruby on Rails By Example

How to check if the variable is defined in Ruby with examples

How to Find the minimum and maximum values in an array and hash Ruby with examples

How to Generate Random number in Ruby with examples

How to Get current Unix timestamp or milliseconds since epoch Ruby Programming| Ruby on Rails by Example