2

The return value of a method is the value of its last statement. This means that Myclass.new following the definition below of the initialize method with super inside:

class Myclass < String
  def initialize(arg)
    super(arg.to_s)
    "something"
  end
end

should return "something". But it returns "test" instead:

Myclass.new("test") # => "test"

Why?

sawa
  • 165,429
  • 45
  • 277
  • 381
medBouzid
  • 7,484
  • 10
  • 56
  • 86
  • 3
    Maybe it's beacause initialize and new are not the same function ? – oldergod Sep 03 '13 at 00:20
  • 1
    The contract of `new` is to return the new object that was created (allocated then initialized). If it returned the result value of when it calls `initialize`, it would obviously not do that. (Unless you ended all implementations of `initialize` with `return self` which would be fantastically annoying.) – millimoose Sep 03 '13 at 00:24
  • 1
    Also, the documentation for `new` literally says the above. (Quote: "Calls `allocate` to create a new object of *class*'s class, then invokes that object’s `initialize` method, passing it *args*.") – millimoose Sep 03 '13 at 00:29
  • this is also a good explanation : http://stackoverflow.com/questions/10383535/in-ruby-whats-the-relationship-between-new-and-initialize-how-to-return-n – medBouzid Sep 03 '13 at 00:40

3 Answers3

8

The class method new

  1. creates a new instance, then
  2. calls the instance method initialize on the instance created, which may return whatever, as in your example, then
  3. returns the instance created.

The return value from initialize to new has no effect on the return value from new.

sawa
  • 165,429
  • 45
  • 277
  • 381
4

You're not calling initialize, you're calling new. The initialize method is essentially a hook that is executed when you create a new object, but it is typically never called directly.

Zach Kemp
  • 11,736
  • 1
  • 32
  • 46
1

If you want to get the return value of your initialize method, you need to call your initialize method. If you call a completely different method, it is only normal that you would get a completely different return value.

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