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/