On 10/15/06, Nicholas Frechette
<nicholas.gravel-frechette / usherbrooke.ca> wrote:
> Consider the following code:
>
> class File
>     alias_method :old_new, :initialize
>
>     def initialize(*args)
>         if args[0] == 'a.txt'
>             # Do not return a file object, return say, a Hash
>             Hash.new
>         else
>             old_new(*args)
>         end
>     end
> end
>
> o = File.new('a.txt')
> puts "Object is of class: #{o.class}"
>
> This outputs:
> Object is of class: File
>
> Any thoughts/help please? I have ran out of ideas... An obvious solution
> is to use a different constructor that is not File.new but that would
> make it not very elegant.

SomeClass#initialize is not SomeClass::new, only the return value of
new decides what the returned object is.
As for overriding Class::new, that's just not necessary and there
probably is a File::new or IO::new that prevents Class::new from being
called.

Try
class File
  alias ...
  def self.new(*args)
    if ...
      return {}
    else
      old_new(*args)
    end
end