存储和检索对象中的变量

时间:2012-08-31 14:18:26

标签: ruby

我想从对象中存储和检索一些变量。例如,在a

a = "a"

到目前为止,我找到了两种可能的方法。

  • 使用instance_variable_setinstance_variable_get

    a.instance_variable_set(:@x, 10)
    a.instance_variable_get(:@x) # => 10
    
  • 或仅使用instance_eval

    a.instance_eval { @y = 5 }
    a.instance_eval { @y } # => 5
    

对我来说,第二种方法看起来更短更简单,如果我更喜欢这个,我的代码有什么问题吗?

2 个答案:

答案 0 :(得分:5)

速度并非一切,但...... instance_variable_set方法比使用instance_eval更快。如果您有兴趣,这是一个基准:https://gist.github.com/1268188

这是另一篇文章,它提供了在可能的情况下避免instance_eval的另一个充分理由:Alex Kliuchnikau on instance_eval

答案 1 :(得分:2)

如果没有充分的理由(例如元编程),你最好避免使用instance_variable_get(set),因为它会打破封装。你可以参考ruby-doc:从而挫败了班级作者试图提供适当封装的努力。

使用instance_eval的最佳做法是编写DSL样式:

假设您有一个具有实例方法的Engineer类:program,play和sleep。所以,

sb = Engineer.new

sb.program
sb.play
sb.sleep

# is equivalent to
sb.instance_eval do
  program
  play
  sleep
end

在这种情况下,它更短:)

相关问题