Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to declare types in Ruby?

Tags:

ruby

I am wanting to clarify if it is not possible to declare types in Ruby or is it just not necessary? If someone wanted to declare datatypes would it be possible.

Update: My point in asking is to understand if providing a static type for variables that won't change type will provide a performance increase, in theory.

like image 876
OpenCoderX Avatar asked Jan 09 '12 17:01

OpenCoderX


2 Answers

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

So, you can't declare variable to some strict type, it will always be dynamic.

like image 137
Oleksandr Skrypnyk Avatar answered Sep 19 '22 15:09

Oleksandr Skrypnyk


What are you trying to do?

You can create your own class:

class Boat
end

If you want an easy way to make a class for holding data, use a struct:

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

You can NOT declare the class of a variable or method argument, like you can in C. Instead, you can check the type at run time:

b.is_a?(Boat)    # Includes subclasses of Boat
b.class == Boat
like image 31
David Grayson Avatar answered Sep 21 '22 15:09

David Grayson