-4

code block

code block

When i create the object as soon above, is the method initliase called first? In PHP, we have something called the constructor with run first whenever an object is created, what if there is more than 1 method in the class, which method is called first in ruby?

Thanks.

Thomas Smyth - Treliant
  • 4,993
  • 6
  • 25
  • 36
zenarthra
  • 17
  • 4
  • This stackoveflow site makes it so hard to learn, what is this stuff about not having enough reputation to post more than 2 links. Absolutely rubbish site, i just want to learn. Not enough reputation to use more keywords. If there is any troubles you should just ban the user, you make it difficult to learn. – zenarthra Sep 12 '16 at 15:08
  • There are plenty of books and tutorials available (interactive ones even). If you don't like the site or its rules don't use it no point in complaining in your own post. Please see this SO post to answer your question http://stackoverflow.com/questions/10383535/in-ruby-whats-the-relationship-between-new-and-initialize-how-to-return-n – engineersmnky Sep 12 '16 at 15:17
  • 3
    Ruby, just like PHP, is text-based. You should therefore post your code as text. – Stefan Sep 12 '16 at 15:19
  • @zenarthra, just write the code contained in the images in your question. Just indent it with four spaces, and you'll be just fine. – Ramses Sep 12 '16 at 15:26

2 Answers2

2

Class#new is just a normal method like any other method. It looks a bit like this, although in most implementations it is actually not written in Ruby:

class Class
  def new(*args, &block)
    new_obj = allocate

    new_obj.initialize(*args, &block)
    # actually, `initialize` is private, so it's more like this instead:
    # new_obj.__send__(:initialize, *args, &block)

    return new_obj
  end
end

The documentation also says it clearly:

new(args, …)obj

Calls allocate to create a new object of class’s class, then invokes that object’s initialize method, passing it args. This is the method that ends up getting called whenever an object is constructed using .new.

Here's the source code for Class#new in the various implementations:

Community
  • 1
  • 1
Jörg W Mittag
  • 363,080
  • 75
  • 446
  • 653
0

the initialize method is called whenever you call new.

Any other methods declared in that class should be called in your code.

For example:

class Example
  def initialize
    #some initialization code here
    puts "initialize method has just been called"
  end

  def foo
    #some foo code
    puts "this is the foo method"
  end 
end 

then, in your code:

my_obj = Example.new #initialize method will be called here

my_obj.foo #now the foo method will be called

That's about it, good luck!

Ramses
  • 996
  • 4
  • 12
  • 28
  • 1
    This is inaccurate. `my_obj = new Example` is invalid syntax in Ruby, it would have to be `my_obj = Example.new` – philomory Sep 12 '16 at 19:39