tags:

views:

44

answers:

2
class Shape
    def initialize()
        @blah = ""
    end
end

OR...will this work?

class Shape
    @blah = ""
    def initialize()

    end
end

Also, by default, are the instance variables public or private? How do you set them as public or private?

+2  A: 

Your second example initializes @blah as a class variable. It wouldn't be directly accessible (it'd need a class accessor) and would be the same across all instances of a class.

Instance variables are private-ish by nature, though you can get access to them with @foo.instance_variable_get("@blah"). Conventionally, if you want to access a @blah instance variable, you would add an accessor.

class Shape
  attr_accessor :blah
end

That would let you say, for example, shape = Shape.new; shape.blah = "whee"; puts shape.blah (and you'd get "whee").

Chris Heald
A class variable would be @@blah.
kiamlaluno
@Chris, i feel that your lastname should be "herald", not "heald". As it is it feels like it's missing something (notably an 'r'). Likewise your answer is missing something...The correct terminology is "class instance variable" not simply "class variable" (which would be @@blah as kiamlaluno correctly points out)
banister
You're both correct. I should avoid SO when tired. And you wouldn't believe the number of telemarketers that pronounce it "Herald". :D
Chris Heald
+1  A: 

Instance variables don't have to be defined anywhere, you can just start using them. But be careful where you use them. Your third example isn't what you want at all.

class Something
  @var = 10
end

This refers to an instance variable of the class Something, not an instance variable of any instance of Something. Just remember not to refer to instance variables outside of the instance methods.

AboutRuby