【发布时间】:2016-05-07 13:54:12
【问题描述】:
我的代码中的一个实例变量不断地重新分配它的值,尽管没有命令它这样做。本质上,该变量只被调用两次:一次,在启动时分配其值,然后将其值复制到另一个变量。我正在处理的代码对我来说有点复杂,所以在这里完整地发布它,但这是它的基本概要:
class Test
def self.initialize
@problem_var = [ ["1 2 3", "4 5 6"], ["a b c", "d e f"], ["bar", "foo"] ]
end
def self.main_method(parVar)
data = @problem_var
result = "Lorem"
#Iterate through subarrays
data.each do |dataBlock|
#Some code here
if condition then
#The first subarray meets the condition
char = dataBlock[1]
#At this point char is equal to "4 5 6"
#@problem_var still holds its original value of:
# [ ["1 2 3", "4 5 6"], ["a b c", "d e f"], ["bar", "foo"] ]
result = OtherModule.replace_six(char)
#By this point, char is now equal to "4 5 7"
#Curiously @problem_var is now equal to:
# [ ["1 2 3, "4 5 7"], ["a b c", "d e f"], ["bar", "foo"] ]
end
end
#More code here
return result
end
end
在result 分配了一个值之后,变量发生了一些奇怪的事情。此外,这似乎只发生一次,因此如果代码再次运行并将 7 更改为... 8,@problem_var 将不会更新。将@problem_var 更改为常量无法防止其被更改。在过去的两周里,我一直在考虑这个问题,但一直无法弄清楚。有人知道会发生什么吗?
编辑:
你们是对的!问题出在 OtherModule 中。我在收到char 的参数变量上使用了gsub!。下面是简化的 OtherModule 代码供将来参考:
module OtherModule
def replace_six(input)
modified_string = ""
if condition(input) then
#Input meets condition
first_string = replace_numbers(input)
#The following method doesn't really apply here
second_string = replace_letters(first_string)
modified_string = second_string
end
return modified_string
end
def replace_numbers(text)
#Some code here
#The following condition for numbers in `text`
if condition(text) then
text.gsub!("6", numberFunction)
#numberFunction returns a string
end
return text
end
end
【问题讨论】:
-
听起来replace_six方法修改了传给它的值
-
分享
OtherModule.replace_six(char)的代码
标签: arrays ruby variables iteration instance-variables