my idea is to create a community wiki for people that come from a java
background because reading a lot of explanations, I couldn't comprehend anything until I actually tried a couple of things and the pieces of the puzzle started to find their places. But I first need to make sure I'm getting it right. Coming from such background it was very confusing for me to find out that @variable
may mean 2 very different things.
Here is an example:
class Test
@ins = "gah"
def self.ins
puts @ins
end
def initialize()
@ins = "wtf?"
end
def ins2
puts @ins
end
end
As far as I understand, the first @ins
is an instance variable of the object representing the class Test
. The second @ins
is an instance variable in an object of class Test
.
Now things start to make some sense to me. Here a couple of examples:
[14] pry(main)> test.ins2
wtf?
We are calling a method of an object and it returns the object's instance variable.
[15] pry(main)> test.ins
NoMethodError: undefined method `ins' for #<Test:0x000000017d9348 @ins="wtf?">
We are trying to call a class method through an object, this method is of the class so we are getting NoMethodError
[16] pry(main)> Test.ins
gah
We are calling a class method so it properly sees the instance variable of the class object.
[17] pry(main)> Test.ins2
NoMethodError: undefined method `ins2' for Test:Class
We are calling an object method through the class which is incorrect so throwing NoMethodError
.
All of the above was performed with ruby 2.0. So what am I asking?
- Am I getting it right?
- Am I getting the ruby terminology correct?
- Any real usage of class instance variables that make sense in a properly designed app? Or are these simply the better @@class variables?
class
then when everything is an object? In any case it becomes offtopic. What I was asking is why call it a "singleton class" instead of a "class" when all classes are like what you're describing above. – Prudenceclass
is useful detail but nothing stops ruby to change class implementation in next version. Unlikely, yes! – Prudence