在您的 process_a_pile_more_records 方法中,您将使用与测试方法中定义的相同引用来实例化方法的参数。
但是,当您执行 iProcessed += 1 时,您实际上是在将 iProcessed 指向一个具有递增值的新对象,而不是递增原始对象。iWorked 也是如此。您将 iWorked 设置为指向 true 的变量。
如果您要针对实际更改底层对象的变量执行方法,那么您将在调用方法中看到 this 的结果。请参阅以下代码示例,其中向 Array 添加元素,修改原始对象或 gsub!方法修改底层字符串。请注意,如果我使用了 gsub 方法,则不会对基础对象进行更改,因为会创建一个新字符串。
请注意,对于 process_a_pile_more_records 的第二次调用,测试方法中的原始变量如何根据 process_a_pile_more_records 方法的返回值赋予新值。
test "local variable manipulation" do
processed = 123
worked = false
string1 = 'Hello'
string2 = 'Goodbye'
an_array = []
process_a_pile_more_records(processed , worked, string1, string2, an_array)
puts 'Output the variables'
puts processed
puts worked
puts string1
puts string2
puts an_array.to_s
processed, worked, string1 = process_a_pile_more_records(processed , worked, string1, string2, an_array)
puts processed
puts worked
puts string1
puts string2
puts an_array.to_s
结尾
def process_a_pile_more_records(processed_var, working_var, first_string, second_string, an_array) (0..10).each do |id| processes_var += 1 working_var = true first_string = first_string + id.to_s second_string.gsub!('oo', '00') an_array << id.to_s end return processes_var, working_var, first_string end
这将产生以下输出:
Testing started at 14:38 ...
Output the variables
123
false
Hello
G00dbye
["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10"]
134
true
Hello012345678910
G00dbye
["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10"]