Instance Variables and Class Variables
suggest changeInstance variables behave like properties of an object. They come into existence when assigned, often in initialize, and instance methods can read them. Each object has its own instance variables. They are not shared between objects.
Sequence class has @from, @to and @by as the instance variables.
class Sequence
include Enumerable
def initialize(from, to, by)
@from = from
@to = to
@by = by
end
def each
x = @from
while x < @to
yield x
x = x + @by
end
end
def *(factor)
Sequence.new(@from*factor, @to*factor, @by*factor)
end
def +(offset)
Sequence.new(@from+offset, @to+offset, @by+offset)
end
end
object = Sequence.new(1,10,2)
object.each do |x|
puts x
end
# Output:
1
3
5
7
9
object1 = Sequence.new(1,10,3)
object1.each do |x|
puts x
end
# Output:
1
4
7
Class variables are shared by a class and its instances, in the same way static fields are shared in Java.
class Sequence
include Enumerable
@@count = 0
def initialize(from, to, by)
@from = from
@to = to
@by = by
@@count = @@count + 1
end
def each
x = @from
while x < @to
yield x
x = x + @by
end
end
def *(factor)
Sequence.new(@from*factor, @to*factor, @by*factor)
end
def +(offset)
Sequence.new(@from+offset, @to+offset, @by+offset)
end
def getCount
@@count
end
end
object = Sequence.new(1,10,2)
object.each do |x|
puts x
end
# Output:
1
3
5
7
9
object1 = Sequence.new(1,10,3)
object1.each do |x|
puts x
end
# Output:
1
4
7
puts object1.getCount
# Output: 2
Shared among object and object1.
Comparing the instance and class variables of Ruby against Java:
Class Sequence{
int from, to, by;
Sequence(from, to, by){// constructor method of Java is equivalent to initialize method of ruby
this.from = from;// this.from of java is equivalent to @from indicating currentObject.from
this.to = to;
this.by = by;
}
public void each(){
int x = this.from;//objects attributes are accessible in the context of the object.
while x < this.to
x = x + this.by
}
}
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents