「Ruby編程語言」 David Flanagan着&松本行弘指出第4.5.2節以下分配到常量分配至恆方法的體內
Assignment to constants is not allowed within the body of a method.
我理解的前提和嘗試的代碼的兩個變化:
PERSONS = {}
def create_persons(filename)
File.foreach(filename).with_index do |line, number|
array = line.split(' ').unshift(number+1)
hash = {:id => array[0],:first_name => array[1], :last_name => array[2], :email => array[3]}
PERSONS = hash
end
end
我得到一個錯誤:
santa.rb:13: dynamic constant assignment
PERSONS = hash
^
我嘗試第二個版本,而不是分配使用相等的運算符,我初始化一個空數組作爲常量,並使用追加運算符將散列追加到空數組。這工作!
PERSONS = []
def create_persons(filename)
File.foreach(filename).with_index do |line, number|
array = line.split(' ').unshift(number+1)
hash = {:id => array[0],:first_name => array[1], :last_name => array[2], :email => array[3]}
PERSONS << hash
end
end
我的問題是爲什麼第二個版本工作時,我使用< <賦值運算符,但不與=賦值運算符的工作。
爲什麼不呢?你不是指定或重新定義常量 - 你正在對該對象*引用的東西做一些事情。 Nitpick:'<<'不是任何形式的任務,這是一種方法。 –
@ dave-newton <<似乎對我來說也是一種方法,也就是它附加。但是在上面引用的同一本Ruby書籍中,它將下面的示例顯示爲縮寫賦值:x << = y(x = x << y) and x >> = y(x = x >> y)這加劇了我的混淆 – PiperWarrior
好吧,@DaveNewton。我現在得到你的評論,並理解賦值(改變對象引用)和修改常量引用的對象(引用同一個對象,但修改)之間的區別。謝謝。 – PiperWarrior