0

I am very familiar with Java but have been venturing out into new languages. In Java, we can declare instance variables outside methods in the body of the class like so:

public class Test {
    public String str = "Hello!";
    public int count = 0;

    public void printString() {
        System.out.println(str);
    }

    public static void main(String[] args) {
        Test t = new Test();
        t.printString();
    }
}

But in Ruby, when I do this, it doesn't print anything:

class Test
    @str = "Hello"

    def print_string
        puts @str
    end
end

t = Test.new
t.print_string

Why can't instance variables be declared in the class body. Isn't this setting attributes for the object? Or does everything have to be set in the initialize method?

  • You have defined a *class* instance variable: `Test.instance_variables #=> [:@str]; Test.instance_variable_get(:@str) #=> "Hello"`. – Cary Swoveland Apr 27 '17 at 06:51
  • instance/member variables should be initialized inside constructor. you can ofcourse create instance/member variables inside instance methods too. – marmeladze Apr 27 '17 at 06:51
  • 1
    @marmelandze, instance variables are created when `self` is the instance, not necessarily by a constructor. – Cary Swoveland Apr 27 '17 at 06:54
  • 1
    There are local variables, class local variables, instance variables, class instance variables, class variables and global variables. Once you learn what each of this is - you'll have an answer to your question (or simply read @CarySwoveland's first comment :)) – Andrey Deineko Apr 27 '17 at 06:57

0 Answers0