【问题标题】:Unexpected return value in ruby红宝石中的意外返回值
【发布时间】:2015-08-03 21:03:02
【问题描述】:
def gen_path_locations(start, destination)
    initial_dest = destination
    last_dest = destination
    path_locations = []
    loop do
        last_dest[0] -= 1 if initial_dest[0] > start[0]
        last_dest[0] += 1 if initial_dest[0] < start[0]
        last_dest[1] -= 1 if initial_dest[1] > start[0]
        last_dest[1] += 1 if initial_dest[1] < start[0]
        break if last_dest == start
        path_locations << last_dest
        puts last_dest.inspect
    end
    path_locations
end

gen_path_locations([5, 5], [9, 9]) 返回[[5, 5], [5, 5], [5, 5]]

它将起始位置添加到我的 path_locations,而不是 last_dest 的当前迭代。当然,如果我把推送改成这样:

path_locations << [last_dest[0], last_dest[1]]

它返回预期值。我错过了什么?

【问题讨论】:

    标签: arrays ruby variable-assignment


    【解决方案1】:

    我错过了什么?

    .clone:

    path_locations << last_dest.clone
    

    否则,您会不断添加内容不断变化的同一个对象;到最后,你仍然会拥有相同的对象 3 次,其内容是你上次更改的内容。

    这里有一个例子来说明:

    a = ["foo", "bar"]
    b = [a, a, a]
    # => [["foo", "bar"], ["foo", "bar"], ["foo", "bar"]]
    a[1] = "quux"
    b
    # => [["foo", "quux"], ["foo", "quux"], ["foo", "quux"]]
    

    您可以看到发生了什么here。该工具不适用于 Ruby,但很高兴该示例也适用于 Python。

    编辑:实际上,here您的代码可视化的链接,被重写为 Python - 您可以逐步查看到底发生了什么。然后用path_locations.append([last_dest[0], last_dest[1]]) 替换追加行,这正是你所做的(也正是Ruby 的clone 所做的更简洁),看看它如何改变程序。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-04-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-04
      • 2019-08-09
      相关资源
      最近更新 更多