Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can new ever return nil?

Tags:

ruby

I am working in a new code base that is written in ruby. I have never developed ruby before, so I have a very general question. The code has a pattern I find weird. When ever it creates a new instance of a class, it immediately checks to make sure it's not nil.

@client = Client.new()
raise("Client not initialized.") if (@client == nil)

In general can new return nil? Is this a common ruby pattern?

like image 785
Dave Avatar asked Sep 11 '15 19:09

Dave


1 Answers

Can it? Yes.

It is possible to override the default implementation of Class#new (which calls Class#allocate and then initialize) with something that might return nil. However,

Will it? Probably not.

The default implementation of new will not return nil, and overriding new is very rare, and probably not great form (although it isn't neccisarily bad practice, there's usually a better way).

like image 187
Linuxios Avatar answered Oct 16 '22 08:10

Linuxios