Zack
Zack

Reputation: 6586

How do I access Ruby type names from within BasicObject

How do I access Ruby type names from within BasicObject? I understand that "... common classes will not be found without using a full class path", but I don't know the syntax for specifying the full class path.

The code below fails because Hash isn't imported into BasicObject.

class Basic < BasicObject
  def flexible(data)
    if (data.is_a?(Hash))
      puts "It's a hash!"
    end
  end
end


foo = Basic.new
foo.flexible({})

Upvotes: 1

Views: 50

Answers (1)

vcsjones
vcsjones

Reputation: 141618

To answer your immediate question, you can access Hash like so:

if (data.is_a?(::Hash))
  puts "It's a hash!"
end

This will still fail for a different reason, which is because BasicObject doesn't include Kernel, so puts is not available:

undefined method `puts' for #<Basic:0x000055c405afbc88>

If you do this as well:

class Basic < BasicObject
  include ::Kernel

or this instead:

::Kernel.puts "It's a hash!"

Then it should work as expected.

Upvotes: 2

Related Questions