Ruby: Initialize() VS Class Body

Ruby: initialize() vs class body?

Try to create two instances of MyClass

a = MyClass.new
b = MyClass.new

to see the difference:

Hello

World

World

Code in the class body execute only once - when ruby loads the file. initialize() executes every time you create a new instance of your class.

What is this property called in a ruby class

It is a class method. Its receiver is the class Person. Allowing the self receiver to be omitted, parentheses to be omitted, the arrow in a hash to be omitted when the key is a symbol, and braces around the hash literal to be omitted in the final-argument position make such DSL possible. If you fully write the method call in the ordinary way, it would look like:

Person.validates(:name, {:presence => true})

Should I put method calls in initialize when using Ruby?

I'd put it right in the initializer like this:

class Calendar

DATE_FORMAT = "%d/%m/%Y"

def initialize(on, off, date_string)
@on = on.to_i
@off = off.to_i
@date = Date.strptime(date_string, DATE_FORMAT)
end
end

Static block in Ruby

I want to create a simple linked list type of an object in ruby; where an instance variable in class points to another instance of same type.

Just a quick note: the word type is a very dangerous word in Ruby, especially if you come from Java. Due to an historic accident, the word is used both in dynamic typing and in static typing to mean two only superficially related, but very different things.

In dynamic typing, a type is a label that gets attached to a value (not a reference).

Also, in Ruby the concept of type is much broader than in Java. In Java programmer's minds, "type" means the same thing as "class" (although that's not true, since Interfaces and primitives are also types). In Ruby, "type" means "what can I do with it".

Example: in Java, when I say something is of type String, I mean it is a direct instance of the String class. In Ruby, when I say something is of type String, I mean it is either

  • a direct instance of the String class or
  • an instance of a subclass of the String class or
  • an object which responds to the #to_str method or
  • an object which behaves indistinguishably from a String.

I want to populate and link all nodes; before the constructor is called and only once. Something that we'd usually do in Java Static block.

In Ruby, everything is executable. In particular, there is no such thing as a "class declaration": a class body is just exectuable code, just like any other. If you have a list of method definitions in your class body, those are not declarations that are read by the compiler and then turned into a class object. Those are expressions that get executed by the evaluator one by one.

So, you can put any code you like into a class body, and that code will be evaluated when the class is created. Within the context of a class body, self is bound to the class (remember, classes are just objects like any other).

Initialize method is a constructor signature in ruby. Are there any rules around them? Like in Java you cannot call another constructor from a constructor if its not the first line (or after calling the class code?)

Ruby doesn't have constructors. Constructors are just factory methods (with stupid restrictions); there is no reason to have them in a well-designed language, if you can just use a (more powerful) factory method instead.

Object construction in Ruby works like this: object construction is split into two phases, allocation and initialization. Allocation is done by a public class method called allocate, which is defined as an instance method of class Class and is generally never overriden. It just allocates the memory space for the object and sets up a few pointers, however, the object is not really usable at this point.

That's where the initializer comes in: it is an instance method called initialize, which sets up the object's internal state and brings it into a consistent, fully defined state which can be used by other objects.

So, in order to fully create a new object, what you need to do is this:

x = X.allocate
x.initialize

[Note: Objective-C programmers may recognize this.]

However, because it is too easy to forget to call initialize and as a general rule an object should be fully valid after construction, there is a convenience factory method called Class#new, which does all that work for you and looks something like this:

class Class
def new(*args, &block)
obj = alloc
obj.initialize(*args, &block)

return obj
end
end

[Note: actually, initialize is private, so reflection has to be used to circumvent the access restrictions like this: obj.send(:initialize, *args, &block)]

That, by the way, is the reason why to construct an object you call a public class method Foo.new but you implement a private instance method Foo#initialize, which seems to trip up a lot of newcomers.

To answer your question: since an initializer method is just a method like any other, there are absolutely no restrictions as to what you can do whithin an initializer, in particular you can call super whenever, wherever, however and how often you want.

BTW: since initialize and new are just normal methods, there is no reason why they need to be called initialize and new. That's only a convention, although a pretty strong one, since it is embodied in the core library. In your case, you want to write a collection class, and it is quite customary for a collection class to offer an alternative factory method called [], so that I can call List[1, 2, 3] instead of List.new(1, 2, 3).

Just as a side note: one obvious advantage of using normal methods for object construction is that you can construct instances of anonymous classes. This is not possible in Java, for absolutely no sensible reason whatsoever. The only reason why it doesn't work is that the constructor has the same name as the class, and anonymous classes don't have a name, ergo there cannot be a constructor.

Although I am not quite sure why you would need to run anything before object creation. Unless I am missing something, shouldn't a list basically be

class List
def initialize(head=nil, *tail)
@head = head
@tail = List.new(*tail) unless tail.empty?
end
end

for a Lisp-style cons-list or

class List
def initialize(*elems)
elems.map! {|el| Element.new(el)}
elems.zip(elems.drop(1)) {|prv, nxt| prv.instance_variable_set(:@next, nxt)}
@head = elems.first
end

class Element
def initialize(this)
@this = this
end
end
end

for a simple linked list?

How to initialize hash so I can use it in a method?

I would not always check for the presence of the hash in the add/etc methods.

This requires always checking for the hash in anything that expects it.

If the class is meant as a wrapper for a file store it only makes sense to create it on instantiation, e.g.,

class SomeClass
def initialize
@files = {}
end

def add_file(name, file)
# Etc.
end
end

It fails with hash creation in the class body because that's at the class, not instance, level, e.g.,

class NotWhatYouExpect
@foo = "bar"
end

@foo is a class instance variable; it belongs to the class NotWhatYouExpect rather than instances of it.



Related Topics



Leave a reply



Submit