Is it possible to declare types in Ruby?

I want to clarify if types can be declared in Ruby or just not needed. If someone wanted to declare data types, that would be possible.

Update. My point is to understand if a static type provides for variables that won't change the type, theoretically will give a performance boost.

+7
source share
4 answers

Some languages, such as C or Java, use a "strong" or "static" variable. Ruby is a “dynamically typed” language, for example, “duck”, which means that the variable dynamically changes its type when the type of the assigned data has changed.

Thus, you cannot declare a variable a strict type, it will always be dynamic.

+10
source

What are you trying to do?

You can create your own class:

class Boat end 

If you need an easy way to make a class for storing data, use struct:

 class Boat < Struct.new(:name, :speed) end b = Boat.new "Martha", 31 

You cannot declare an argument class of a variable or method, as you can in C. Instead, you can check the type at runtime:

 b.is_a?(Boat) # Includes subclasses of Boat b.class == Boat 
+4
source

One suggestion is to add typing to Ruby http://bugs.ruby-lang.org/issues/5583 by Yasushi Ando ( parse.y famtour ). My favorite comment:

(b) not sure how he can honor duck typing. I think the whole idea is (optional) to fry the duck!

+3
source

If I understood correctly what you mean with type , each Class in Ruby defines a type.

 1.class # => Fixnum 

You can create a class to define a custom type.

 class Book end b = Book.new b.class # => Book 
+2
source

All Articles