例項變數和類變數
讓我們首先了解一下例項變數: 它們的行為更像是物件的屬性。它們在物件建立時初始化。例項變數可通過例項方法訪問。每個物件具有每個例項變數。例項變數不在物件之間共享。
Sequence 類有 @ from,@ to 和 @by 作為例項變數。
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
類變數將類變數視為 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
在 object 和 object1 之間共享。
比較 Ruby 與 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
}
}