开发者

Ruby Instance Variable Scope Question

开发者 https://www.devze.com 2023-01-16 09:46 出处:网络
I come from C++ and JAVA, which with Scope there is either gl开发者_如何学Cobal or local. I\'m now learning ruby-on-rails and with ruby there is local, instance and global. I\'ve never really heard o

I come from C++ and JAVA, which with Scope there is either gl开发者_如何学Cobal or local.

I'm now learning ruby-on-rails and with ruby there is local, instance and global. I've never really heard of instance till now.

With or without rails, what is the understanding and usage of the instance variable?

Global = Variable across all objects share
Instance = Variable inside of the object
Local = Variable inside of the object

I think I'm getting instance and local kinda mixed together.

@ham
ham

These are two different variables right? Sometimes I get confused in Rails because they use stuff interchangably like @something and :something. Why is that?

Because I use the rails framework, all I understand the instance variable to be is something that is accessible by the view.

Can someone clarify these variables?


Instance variable in Ruby is like the one in Java, part of object state:

class MyObject
  def set_x(x)
    @x = x
  end

  def get_x
    @x
  end
end

Equivalent Java code:

class MyObject {
    private Object x;

    void setX(Object x) {
        this.x = x;
    }

    Object getX() {
        return x;
    }
}

And local variable is just a variable accessible only within this particular method:

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);
}

edit
What do you mean by object state?

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()'


Those with colon (:something) are symbols.

http://glu.ttono.us/articles/2005/08/19/understanding-ruby-symbols

0

精彩评论

暂无评论...
验证码 换一张
取 消