Determining type of an object?

How do you get the type of an object in ruby?

There are many ways to convert a number to a string in Ruby.

The most common way is to use the to_s method:

1.to_s # => "1"
2.to_s # => "2"

The to_s method can also be used with a base argument to convert a number to a string in a different base:

10.to_s(2) # => "1010"
10.to_s(8) # => "12"
10.to_s(10) # => "10"
10.to_s(16) # => "a"

If you need to convert a number to a floating point string, you can use the to_f method:

1.to_f # => 1.0
2.to_f # => 2.0

If you need to convert a number to a rational string, you can use the to_r method:

1.to_r # => (1/1)
2.to_r # => (2/1)

If you need to convert a number to a complex string, you can use the to_c method:

1.to_c # => (1+0i)
2.to_c # => (2+0i)

There are no primitive types in Ruby - hence, there’s no typeof. Everything is an object in Ruby, some of the things can be a module, while the rest are instance of classes. To determine the class, we simply use .class() method on the object.

Anything has the .class() method. For example:

> 'hello'.class` # => String
> 'hello'.class.class # => Class
> 5.class # => Integer
> Module.class # => Class
> Class.class # => Class
> { }.class # => Hash
> Class.new { define_method(:x) { 5 } }.new.class # => #<Class:0x000055c793e9ea70>
> X = Class.new { } ; X.new.class # => X
> x = Class.new { } ; x.new.class # => #<Class:0x000055c793517a10>

And so on. It works on all Objects.

2 Likes