变量改变时调用的钩子 [英] Hook to be called when a variable changes

查看:29
本文介绍了变量改变时调用的钩子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

ruby 中是否有一个钩子,每次某个变量的值改变时都会调用它?

Was there a hook in ruby that is called every time the value of a certain variable changes?

推荐答案

如果你为 Ruby 编写了一个 C 扩展,你实际上可以创建一个全局变量,只要有人设置它就会触发一个 setter 钩子.

If you write a C extension for Ruby, you can actually make a global variable that triggers a setter hook whenever someone sets it.

但您可能不想这样做,因为您必须编写一些 C 语言,而管理它可能会很痛苦.

But you probably don't want to do that because you'd have to write some C and it could be a pain to manage that.

更好的策略是通过适当的方法读取和设置变量.然后当 setter 方法被调用时,你可以做任何你想做的事情.下面是一个将变量封装在对象中的示例:

A better strategy would be to make it so that the variable is read and set through appropriate methods. Then when the setter method is called you can do whatever you want. Here is an example that encapsulates a variable inside an object:

class Foo
  def bar=(v)
    @bar = v
    # do some stuff
  end

  def bar
    @bar
  end
end

同样,您可以将变量封装在模块或类中,而不是对象中.

Similarly you could encapsulate the variable in a module or class instead of an object.

这篇关于变量改变时调用的钩子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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