gpt4 book ai didi

Ruby Map 方法编辑原始数组?

转载 作者:行者123 更新时间:2023-12-05 00:41:19 25 4
gpt4 key购买 nike

def removal(arr)
letters ="i"
p arr
new_array = arr.map do |c_word|
c_word.each_char.with_index do |char, index|
if letters.include?(char)
c_word[index] = "*"
end
end
end
p arr #the original array is getting edited? why?
p new_array

end

removal(["hiiiiiigh","git", "training"])

在这段代码中,map 方法中的原始数组 (arr) 不断被编辑。我认为该 map 不会编辑原始数组。如果我需要编辑原件,我会使用 .map!

我相信它与嵌套枚举器或我没有看到的变量引用有关。而不是 each_char.with_index,我使用了一个 while 循环,map 仍然会编辑原始数组。为什么要编辑原始数组?

最佳答案

您实际上在(至少)两个地方是错误的:

  • map未编辑原始数组
  • 事实上,原始数组根本没有被编辑

  • 如果仔细观察,数组并没有改变,只有数组内部的字符串发生了变化。而且不是 map就是这样做的,它是 String#[]= ,你在这里打电话:
    c_word[index] = "*"

    因此,您正在调用一个编辑字符串的方法,您应该不会对您的字符串被编辑感到惊讶!

    关于Ruby Map 方法编辑原始数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58351516/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com