English 中文(简体)
Hooks在变数变化时被称作
原标题:Hook to be called when a variable changes

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

最佳回答

如果你写出对鲁比拉的C级延伸,你实际上能够形成一个全球性的变数,在有人提出时触发一个固定的 h。

但是,你可能不想这样做,因为你必须写一些C,而管理起来可能是痛苦的。

更好的战略是使之能通过适当方法阅读和确定变量。 然后,当有人叫你时,你可以做你想要的一切。 这里的一个例子是,在物体内形成变量:

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

  def bar
    @bar
  end
end

同样,你可以将变数归入模块或类别而不是物体。

问题回答

序言: 我不是解决办法(第一点已经写过:没有,但也许可以在特殊情况下提供帮助)。

我的第一个想法是使用<代码> 冻结<>代码/代码>,以便找到解决办法:

a = "aa"
a.freeze
a <<  b   #can t modify frozen string (RuntimeError)

现在我们必须重新界定<代码> 冻结<>>。

module FreezeWarning
  def freeze
    puts "#{self}: I am changed"
  end
end

a = "aa"
a.extend(FreezeWarning)
a.freeze
a <<  b   #aa: I am changed

第一期: 无法获得可变名称

You may solve this with an additional variable (You can define your own variable identification, it must not be the name)

module FreezeWarning
  def change_warning(name)
    @varname = name
    self.freeze
  end
  def freeze
    puts "<#{@varname}> (#{self}): I am changed"
  end
end

a = "aa"
a.extend(FreezeWarning)
a.change_warning( a )
a <<  b   #<a> (aa): I am changed

但更大的问题: 这只具有价值的变化,而不是新的任务:

a = 5
a.freeze
a = 4
p a  # -> 4

因此,这只是一个非常有限的解决办法。





相关问题
Ruby parser in Java

The project I m doing is written in Java and parsers source code files. (Java src up to now). Now I d like to enable parsing Ruby code as well. Therefore I am looking for a parser in Java that parses ...

rails collection_select vs. select

collection_select and select Rails helpers: Which one should I use? I can t see a difference in both ways. Both helpers take a collection and generates options tags inside a select tag. Is there a ...

RubyCAS-Client question: Rails

I ve installed RubyCAS-Client version 2.1.0 as a plugin within a rails app. It s working, but I d like to remove the ?ticket= in the url. Is this possible?

Ordering a hash to xml: Rails

I m building an xml document from a hash. The xml attributes need to be in order. How can this be accomplished? hash.to_xml

multiple ruby extension modules under one directory

Can sources for discrete ruby extension modules live in the same directory, controlled by the same extconf.rb script? Background: I ve a project with two extension modules, foo.so and bar.so which ...

Text Editor for Ruby-on-Rails

guys which text editor is good for Rubyonrails? i m using Windows and i was using E-Texteditor but its not free n its expired now can anyone plese tell me any free texteditor? n which one is best an ...

热门标签