Struct both has and does not have an allocator
One the one hand:
>> Struct.allocate TypeError: allocator undefined for Struct from (irb):1:in `allocate' from (irb):1 from /opt/Ruby/1.9.3-p327/bin/irb:12:in `<main>'
But on the other:
>> Struct.method(:allocate) => #<Method: Class#allocate>
In my current case, I need a reliable way to check if a class can be allocated or not. How can one do this if the method is remains present even when it can not be used?
#1 [ruby-core:51859] Updated by Yukihiro Matsumoto almost 4 years ago
- Status changed from Open to Closed
"allocator" in the error message does not mean #allocate method, but internal C function (thus TypeError not NoMethodError).
We haven't provide the way to check if a class can be allocated, except for actually allocating an object.
I don't think we need to prepare the way to check explicitly.
#4 [ruby-core:51878] Updated by Thomas Sawyer almost 4 years ago
But is not so nice to have to write code like this:
success = begin object = type.allocate true rescue TypeError false end if success ... else ... end
Instead of like:
begin object = type.allocate ... rescue TypeError ... end
Can't do it b/c what if first
... code causes different TypeError?
Actually the more I think about it the more I am inclined to add a core extension:
def try_allocate begin allocate rescue TypeError nil end end
Then we could write:
if object = try_allocate ... else ... end
#5 [ruby-core:51880] Updated by Eric Hodel almost 4 years ago
Sounds like you are reinventing begin; rescue; else; end: https://github.com/ruby/ruby/blob/trunk/doc/syntax/exceptions.rdoc
#7 [ruby-core:51887] Updated by Thomas Sawyer almost 4 years ago
Ok. One last comment on this:
I am not positive about adding exception classes. So far, TypeError only caused by inexistence of allocator.
Assessments like "So far", are what make's a coder worry. In future that could change, then my code suddenly has potential error in it. However, I realize this is very unlikely, so I won't fret over it. But unlikely or no, I'd rather have zero probability of worry!
P.S. @drbrain It worked. Thanks again.