Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby Instance Variable Scope Question

Tags:

scope

ruby

I come from C++ and JAVA, which with Scope there is either global 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?

like image 822
RoR Avatar asked Sep 17 '10 18:09

RoR


2 Answers

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()'
like image 98
Nikita Rybak Avatar answered Nov 15 '22 08:11

Nikita Rybak


Those with colon (:something) are symbols.

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

like image 22
Namek Avatar answered Nov 15 '22 08:11

Namek