OpenCoderX
OpenCoderX

Reputation: 6318

Is it possible to declare types in 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.

Upvotes: 12

Views: 15690

Answers (4)

Oleksandr Skrypnyk
Oleksandr Skrypnyk

Reputation: 2830

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.

Upvotes: 16

Andrew Grimm
Andrew Grimm

Reputation: 81570

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

(b) not sure how it can honor duck typing. i think the whole idea is to (optionally) roast the duck!

Upvotes: 6

David Grayson
David Grayson

Reputation: 87486

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

Upvotes: 6

Simone Carletti
Simone Carletti

Reputation: 176472

If I correctly understood 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

Upvotes: 2

Related Questions