ruby - 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 仍然会编辑原始数组。为什么要编辑原始数组?
解决方案
您实际上在(至少)两个地方是错误的:
map
没有编辑原始数组- 事实上,原始数组根本没有被编辑
如果仔细观察,数组并没有改变,只有数组内部的字符串发生了变化。不是map
that 这样做,而是String#[]=
,您在这里调用它:
c_word[index] = "*"
所以,你正在调用一个编辑字符串的方法,你不应该对你的字符串被编辑感到惊讶!
推荐阅读
- flutter - Flutter中如何使用Webview自动填充数据?
- kubernetes - Kubernetes / Agones 服务缩减
- tableau-api - Tableau 服务管理器与 Tableau Server 一起安装在哪里?
- javascript - 错误:无法从源(未定义)SANITY.IO 解析图像 URL
- java - 如何检测我的 whatsapp/telegram/messenger 的外出电话是否被接听?
- selenium - 无法获取页面上的特定元素,将 xpath 用于 Selenium 脚本
- laravel - Cookie 的两种喜欢
- javascript - 如何在 React 中多次提交同一个表单
- angular - ngFor 带有 mat 选择选项中的对象的 netsted 数组
- android-studio - Android Studio 陷入索引