undefined method `exist?' - Feature... or bug?

Viewed 58

I found some unexpected (to me) behavior in Ruby. Is this behavior a bug or a feature? I stumbled on this situation while writing my project.

To put it as succinctly as I can: if a class' name ends with ::File and that class inherits from another class, then the usual File class isn't used with "File", but instead the current class is used.

(Yes, that's as succinct as I could figure out how to make it.)

Consider the following code, which produces the [feature|bug]

class MyClass
end

class MyClass::File < MyClass
    def check
        File.exist?('./whatever.txt')
    end
end

myfile = MyClass::File.new
myfile.check

That code produces the following error:

./dev.rb:8:in `check': undefined method `exist?' for MyClass::File:Class (NoMethodError)
Did you mean?  exit
               exit!
    from ./dev.rb:13:in `<main>'

What's weird (to me, anyway) is that the error doesn't happen if MyClass::File doesn't inherit from MyClass. That is, if you remove the "< MyClass" part then there's no error.

Now, I can just hear some programmers muttering over their latte: you shouldn't end a class name with ::File, that's just bad form. Well, I really want my class called ::File because that's the type of object it represents. I just have this thing that I like to give classes meaningful names.

I found a work around by calling Object::File instead of just File:

Object::File.exist?('./whatever.txt')

I don't even know how I figured that out... I couldn't google anything about this [feature|bug] but I figured it out within 20 guesses. Got lucky, I guess.

So...

1) Is this a feature or a bug? 2) Did I use the right workaround?

0 Answers
Related