views:

412

answers:

3

Hi.

I have been a Java programmer for a while and I am trying to switch to ruby for a while. I was just trying to develop a small test program in ruby and my intention is something like following.

  1. 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.
  2. 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.

  3. 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?)

Thanks for the help. -Priyank

A: 

You can simply initialize your class variables in the class body, outside of any method declaration. It will behave like a static initializer in Java:

class Klass
   @@foo = "bar"

   def sayFoo
      puts @@foo
   end

   def self.sayFoo
      puts @@foo
   end

 end

The class field @@foo is here initialized to "bar".

paradigmatic
The questioner was talking about instance and not class variables
johannes
He was talking about *static blocks* in java (see the title and the point 2). They are used to initialize class variables in java.
paradigmatic
A: 

In ruby object creation works like this

class Class
  def new(*args)
    obj= self.allocate # get some memory
    obj.send(:initialize) # call the private method initialize
  end
end
  • Object#initialize is just an ordinary private method.
  • If you wan't something to happen before Object#initialize you have to write your own Class#new. But I see no reason why you would want to do that.
johannes
+9  A: 

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?

Jörg W Mittag
great answer Thanks! Gave me a lot of insight.
Priyank
Fantastic answer. Thank you!
Mike