I want to define a class which happens to have the same name as a
builtin class. It shouldn't be a problem because it's in an extra
namespace, but Ruby opens the existing class instead of defining a new
one. Here's an example:
module MyNamespace
class Array
# Some stuff
end
end
I tried using the full qualifier (class MyNamespace::Array) but it
didn't help. Is there a possibility to actually define a new class?
I want to define a class which happens to have the same name as a
builtin class. It shouldn't be a problem because it's in an extra
namespace, but Ruby opens the existing class instead of defining a new
one. Here's an example:
module MyNamespace
class Array
# Some stuff
end
end
That's fine. What makes you think that this didn't create a separate
class?
I tried using the full qualifier (class MyNamespace::Array) but it
didn't help.
In what way didn't it help? Did you get an error message? Post your full
code and the exception.
Is there a possibility to actually define a new class?
Sure, you've just done it
module MyNamespace; class Array; end; end
=> nil
Array.object_id
=> 70098182563360
MyNamespace::Array.object_id
=> 70098182326040
a = MyNamespace::Array.new
=> #<MyNamespace::Array:0x7f820281f520>
a[1]
NoMethodError: undefined method `' for
#<MyNamespace::Array:0x7f820281f520>
from (irb):5
All of a sudden, the scales fall from my eyes. At first I wasn't so sure
whether I defined a new class or not myself. I looked at the methods of
the class and something made me think that they were the same as
`Array`s. Retrospectively, I don't know what made me think so. Thanks
for your help.
Just adding 0.02EUR: creation of a class with the same name as one of
the core classes does not seem like a good idea to me - although it's
certainly possible. It may cause confusion and it also makes using
the core class more cumbersome (you need to reference it as ::Array in
the module and nested classes for example).
Kind regards
robert
···
On Thu, Sep 23, 2010 at 9:59 PM, Hagbard Celine <sin3141592@gmail.com> wrote:
All of a sudden, the scales fall from my eyes. At first I wasn't so sure
whether I defined a new class or not myself. I looked at the methods of
the class and something made me think that they were the same as
`Array`s. Retrospectively, I don't know what made me think so. Thanks
for your help.
creation of a class with the same name as one of
the core classes does not seem like a good idea to me - although it's
certainly possible. It may cause confusion and it also makes using
the core class more cumbersome (you need to reference it as ::Array in
the module and nested classes for example).
That's true but unfortunately `Array` is just the perfect name for my
class. I rather use MyNamespace::Array and ::Array instead of inventing
a bad-fitting name for the class.