我来自C和JAVA,其中Scope有全球或本地.
我现在正在学习ruby-on-rails和ruby,有本地,实例和全局.直到现在我才真正听说过这个例子.@H_404_3@
有或没有rails,实例变量的理解和用法是什么?@H_404_3@
Global = Variable across all objects share Instance = Variable inside of the object Local = Variable inside of the object
我想我的实例和当地有点混合在一起.@H_404_3@
@ham ham
这两个不同的变量对吧?有时我在Rails中感到困惑,因为他们使用的东西可以像@something和:某些东西.这是为什么?@H_404_3@
因为我使用rails框架,所以我理解实例变量是视图可以访问的东西.@H_404_3@
有人可以澄清这些变量吗?@H_404_3@
解决方法
Ruby中的实例变量与Java中的实例变量类似,是对象状态的一部分:
class MyObject def set_x(x) @x = x end def get_x @x end end
class MyObject { private Object x; void setX(Object x) { this.x = x; } Object getX() { return x; } }
而局部变量只是一个只能在这个特定方法中可访问的变量:@H_404_3@
def doIt x = 3; # x not accessible from outside of doIt puts x end void doIt() { int x = 3; // same in Java System.out.println(x); }
编辑
对象状态是什么意思?@H_404_3@
MyObject o = new MyObject(); o.setX(3); // integer 3 is now stored in variable 'x' of object 'o' // I can return any time later and get that value back by 'o.getX()'