我想从对象存储和检索一些变量.例如在a
a = "a"
Run Code Online (Sandbox Code Playgroud)
到目前为止,我发现了两种可能的方法.
使用instance_variable_set和instance_variable_get
a.instance_variable_set(:@x, 10)
a.instance_variable_get(:@x) # => 10
Run Code Online (Sandbox Code Playgroud)或者只是使用 instance_eval
a.instance_eval { @y = 5 }
a.instance_eval { @y } # => 5
Run Code Online (Sandbox Code Playgroud)对我来说第二种方法看起来更短更简单,如果我喜欢这个,我的代码有什么问题吗?
速度并非一切,但...... instance_variable_set方法比使用更快instance_eval.如果你有兴趣,这是一个基准:https://gist.github.com/1268188
这是另一篇文章,它提供了另一个instance_eval在可能的情况下避免的理由:Alex Kliuchnikau在instance_eval上
| 归档时间: |
|
| 查看次数: |
155 次 |
| 最近记录: |