【发布时间】:2017-11-07 15:01:21
【问题描述】:
以下代码不起作用,问题出在 calc_fitness 方法内部,每个块都没有返回值,我不知道为什么
# takes an array, splices them into groups of 2 and returns a sum of values read from the matrix
def calc_fitness(hypothesis_arr)
hypothesis_arr.each_slice(2).to_a.map{|v| $distances[v.first,v.last]}
end
def main
# filling the matrix, with random values
$distances = create_sym_matrix
p calc_fitness((0..99).to_a)
end
main
# => [67,67,67,67....67,] #these should not be the same, which means i the block alway returns the same value. Why?
【问题讨论】:
-
ruby 中的所有内容都返回一个值。恰好 main 的返回值是
nil,因为来自hypothesis_arr.each_slice(2).each{|v| $distances[v.first,v.last]}的返回值是nil。您可以通过(0..99).to_a.each_slice(2).each{} #=> nil重新创建它 -
在使用像
$distances这样的全局变量时要格外小心,这就是$前缀的含义。这些可以使其他普通代码在匆忙中完全无法维护。同样,没有理由使用main方法,Ruby 已经为此目的提供了main上下文,即任何类、模块或方法定义之外的代码。