Yehudi
Yehudi

Reputation: 199

Ruby inner class of Hash

for example

class C1
     class Hash
       def ok?
          return 'nested hash ok'
       end
      end
     def m1
        return Hash.new.ok?
     end
     def m2
        return {}.ok?
     end
end

the C1.new.m1 works but C1.new.m2 not. what's the different meaning in naming space?

Upvotes: 0

Views: 199

Answers (2)

Zabba
Zabba

Reputation: 65467

You simply created a new class called Hash, nested inside C1.

You did not add a method to Ruby's Hash class as you were expecting. If you wanted that, move the class Hash outside of C1 and re-run: the code will perform as expected.

As your current code is, presume you named the nested class as MyThing. Now, you would not work {}.ok? to work, would you?

So to recap:

This would work:

class Hash
   def ok?
    return 'non-nested hash ok'
   end
end
class C1
     def m1
        return Hash.new.ok? #WORKS
     end
     def m2
        return {}.ok? #WORKS
     end
end

This will fail:

class C1
    class MyThing
      def ok?
       return 'nested hash ok'
       end
    end
     def m1
        return MyThing.new.ok? #WORKS
     end
     def m2
        return {}.ok? #FAILS
     end
end

Upvotes: 3

Reactormonk
Reactormonk

Reputation: 21690

class C1
  class Hash # defines C1::Hash
    def ok?
      return 'nested hash ok'
    end
  end

  def m1
    return Hash.new.ok? # refers to C1::Hash
  end

  def m2
    return {}.ok? # refers to Hash
  end
end

There is no mixing of classes based on namespaces. They are separate.

Upvotes: 0

Related Questions