M
M
Meridian3122013-12-22 06:20:28
ruby
Meridian312, 2013-12-22 06:20:28

What is the difference between a constructor and an initialize method in Ruby?

As I understand it, since Ruby is dynamic, when creating an object, it is necessary to assign fields to it to manage the state of the object, and this happens with the help of initialize. For me, a constructor initializes variables with values.
What if I have 2 initialize methods with different signatures and why can't initialize be called an object constructor?

class A

  def initialize(param1, param2)
    @param1, @param2 = param1, param2
  end

  def initialize(param1)
    @param1 = param1
  end

  def m1
    puts @param2
  end

end

# Почему m1 не выводит ни ошибку, ничего
s = A.new ("val")
s.m1

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry, 2013-12-22
@Meridian312

1. Ruby does not support methods with different signatures. But instead of an error, it simply takes the last computed one. In your case, the first init method will be overwritten by the second. For example, swap them and the call A.new(1)will return an error about insufficient arguments.
The roots of this problem stem from Ruby's dynamism and lack of pattern matching.
2. initialize cannot be called a constructor, because the constructor is actually a new class method. And in A.newthe instance method initialize is always called, if it is present. But this is such a minor remark that you can also call initialize a constructor, the error is not significant at this stage.
Regarding several constructors - here's a template for you:

def initialize(*args)
  if args.length == 1
    #initialize method 1
  else
    #initialize method 2
  end
end

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question