trosborn
trosborn

Reputation: 1668

Are Symbols in Ruby Made with Constructors or Initializers?

In the answer to this SO question Jörg W Mittag says:

There is no such thing as a constructor in Ruby.

I didn't think much of that, until I read the Wikipedia article on constructors, which states:

Immutable objects must be initialized in a constructor.

Since symbols are immutable in Ruby, how are they made? Wikipedia would seem to think they must be made with a constructor, yet Jörg says there are no constructors in Ruby.

I'm fairly new to OOP concepts and programming in general, so it possible I am missing something fairly basic, but from my perspective it there is a contradiction between these sources.

Upvotes: 2

Views: 146

Answers (2)

jrochkind
jrochkind

Reputation: 23337

Symbols are 'initialized' in some dark inside part of the ruby runtime, that you don't need to worry about.

If you make your own immutable class in ruby, it would have to be initialized in it's "constructor", which in ruby means in it's #initialize method. The initialize method may or may not technically be a constructor, but it's the method that is called when the object is instantiated, which is the point the wikipedia article is making -- since an immutable object can't be changed once created, any state has to be set when it's created, not later.

Wikipedia article calls this 'a constructor', but different languages use different terminology or exact constructs, the wikipedia article wasn't written with ruby in mind. For ruby, "place you can set state on object instantiation" is typically initialize method. (I say 'typically', because you can do all kinds of crazy things in ruby if you try). The wikipedia article is still right that if an object is truly immutable, any setting of state happens to happen on object creation, not afterwords -- that's just the meaning of 'immutable', right?

That's for immutable classes implemented by ruby source code. But good luck finding an 'initialize' method for symbols. They don't work that way. They are just provided by ruby itself, by the runtime, and we don't need to worry about the details.

Upvotes: 2

mipadi
mipadi

Reputation: 410932

When people say

There is no such thing as a constructor in Ruby.

they mean that there is no special method type corresponding to a constructor, the way there is in C++ and Java.

In Ruby, the initialize method is, by convention, used to initialize a new object. However, it is not a special method -- it's a method just like any other method in Ruby.

Upvotes: 2

Related Questions