首页 > 解决方案 > Ruby Map 方法编辑原始数组?

问题描述

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!

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

标签: rubydictionaryreferenceenumerate

解决方案


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

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

如果仔细观察,数组并没有改变,只有数组内部的字符串发生了变化。不是mapthat 这样做,而是String#[]=,您在这里调用它:

c_word[index] = "*"

所以,你正在调用一个编辑字符串的方法,你不应该对你的字符串被编辑感到惊讶!


推荐阅读