【发布时间】:2016-06-01 03:02:50
【问题描述】:
David Flanagan 和 Yukihiro Matsumoto 所著的“Ruby 编程语言”在第 4.5.2 节分配给常量中陈述了以下内容
在方法体中不允许给常量赋值。
我理解了前提并尝试了两种代码变体:
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 >= y (x = x >> y)。这增加了我的困惑。
-
好的,@DaveNewton。我现在得到您的评论,并了解分配(更改对象引用)和修改常量引用的对象(引用是同一个对象,但已修改)之间的区别。谢谢。