I feel it is weird to create an object by calling “new”, but in class definition the initializer is called “initialize”. I tried to make it consistent(to be called “new” in both class definition and outside) so I tried the code below using alias_method:
class Class
alias_method :initialize :new
end
class Foo
def new
puts "bar"
end
end
f = Foo.new
I thought when I alias new as initialize, it will call initialize, and initialize is the alias of new so it will call new. But it is not working, and give errors:
SyntaxError: test.rb:2: syntax error, unexpected ':'
alias_method :initialize :new
^
Apparently new is a key word and cannot be aliased. But any way around?
Update:
Sorry I missed the comma in the alias_method
After adding the comma, the script runs without error. But it does not output “bar” so new method is not called. I am not sure why this will not work as comments below…
I have no idea what the implications are for overriding
Object#initialize. I wouldn’t sleep well at night with this in my code but how about something like: