简体   繁体   English

如何从BasicObject中访问Ruby类型名称

[英]How do I access Ruby type names from within BasicObject

How do I access Ruby type names from within BasicObject ? 如何从BasicObject访问Ruby类型名称? 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 . 下面的代码失败,因为Hash没有导入到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({})

To answer your immediate question, you can access Hash like so: 要回答您的直接问题,您可以像这样访问Hash

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: 由于其他原因,这仍然会失败,这是因为BasicObject不包含Kernel ,因此puts不可用:

undefined method `puts' for #<Basic:0x000055c405afbc88> #<Basic:0x000055c405afbc88>的未定义方法`puts'

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. 然后它应该按预期工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM