Reputation: 91
I want to know if there is any ruby function or method to find out the type of object (Integer
, String
, Symbol
, etc.).
Upvotes: 5
Views: 27692
Reputation: 10358
You could call class method
on object
obj.class
For Instances
:test_1.class => Symbol
Or you could also Used: instance_of? Method
puts 10.instance_of? Fixnum #=> True
puts [1,2].instance_of? Array #=> True
for more Info you could determining-type-of-an-object-in-ruby see this
Upvotes: 8
Reputation: 1864
42
is an instance of Fixnum
, Fixnum
is a subclass of Numeric
.
4.2
is an instance of Float
, Float
is a subclass of Numeric
as well.
42.kind_of? Numeric
=> true
(4.2).kind_of Numeric
=> true
Upvotes: -1
Reputation: 106027
The assumption you've made is that if the value returned by a mathematical operation is an integer, the value's class will be Fixnum. That's not correct.
Take a look:
a = 5
puts a.class
# => Fixnum
b = 5.0
puts b.class
# => Float
Mathematically speaking, 5 and 5.0 are the same number and that number is an integer. But 5 and 5.0 in Ruby (like many other programming languages) are not the same. One is a fixed-point value (ergo Fixnum) and the other is a floating-point value (Float). A Fixnum can represent integers only, but a Float can represent both integers and fractions (but, it behooves me to mention, not all fractions).
In Ruby, when you do a mathematical operation with two Fixnums, a Fixnum is returned:
a = 4
puts a.class # => Fixnum
x = a ** 2
puts x # => 16
puts x.class # => Fixnum
However, if either number is a Float, a Float is returned:
a = 4
x = a ** 2.0
puts x # => 16.0
puts x.class # => Float
b = 4.0
puts b.class # => Float
y = b ** 2
puts y # => 16.0
puts y.class # => Float
y = b ** 2.0
puts y # => 16.0
puts y.class # => Float
You asked how to "find the type of an object," and the answer to that question is to use the Object#class
method, as above. But as you can see, "Is the object a Fixnum?" and "Is the object an integer?" are two different questions.
If you want to know if a number in Ruby is an integer even if it's a Float, refer to the excellent answers to this question: Checking if a Float is equivalent to an integer value in Ruby
Upvotes: 17