有没有一种方法可以覆盖Ruby中的实例变量查找? [英] Is there a way to override instance variable lookup in Ruby?

查看:72
本文介绍了有没有一种方法可以覆盖Ruby中的实例变量查找?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果未初始化变量而不是nil,请问是否要返回其他内容.这可能吗?我只想在每个班级重载它,而不是全局重载.

Say if I want to return something else if a variable isn't initialized instead of nil. Is this possible? I'd like to only overload it per class, not globally.

(原因主要是玩疯狂的把戏).

(The reason for this is mainly to play with crazy tricks).

推荐答案

在这种情况下,您可以使用#instance_variable_defined?#instance_variable_get.例如:

In that case, you could use #instance_variable_defined? and #instance_variable_get. For instance:

class Thing
  def method_missing(method, *args, &block)
    ivar_name = "@#{method}".intern

    if instance_variable_defined? ivar_name
      instance_variable_get ivar_name
    else
      super method, *args, &block
    end
  end
end

将为任何设置的实例变量自动定义实例变量读取器,或者:

would automatically define instance variable readers for any set instance variables, or:

class Thing
  IVARS = [:@first, :@second]

  def method_missing(method, *args, &block)
    ivar_name = "@#{method}".intern

    if IVARS.include? ivar_name
      if instance_variable_defined? ivar_name
        instance_variable_get ivar_name
      else
        "your default"
      end
    else
      super method, *args, &block
    end
  end
end

如果IVARS常量中命名的实例变量(默认为默认值),则

会定义任何读取器.我确定您可以看到如何将其更改为哈希映射实例变量名称为其默认值或其他任何值.

would define readers for any if the instance variables named in the IVARS constant, defaulting to the default value. I'm sure you can see how you could change that to be a hash mapping instance variable names to their default values or whatever.

或者,如果您不需要其他任何灵活性,则可以简单地使用instance_variable_get提供默认值:

Or you could simply use instance_variable_get to provide a default value if you don't need any more flexibility than this:

thing = Thing.new
thing.instance_variable_get :@ivar_name, "your default"

尽管这不会定义读取器方法-您每次都必须通过instance_variable_get访问.

although this would not define reader methods - you would have to access via instance_variable_get each time.

这篇关于有没有一种方法可以覆盖Ruby中的实例变量查找?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆