在 Ruby 多维数组中查找和替换
有没有一种优雅的方法来查找和替换多维数组中大于 3 的任何整数(例如)?该数组的维度可以是 1、2、3 或更多。只是此类数组的一个示例:
[ [ [ 3, 3, 5 ],
[ 4, 3, 3 ] ],
[ [ 3, 2, 3 ],
[ 0, 3, 8 ] ] ]
我想在不展平数组的情况下这样做。
Is there an elegant way to find and replace any integers superior to 3 (as example) in a multidimensional array? The array may have the dimension 1, 2, 3, or more. Just an example of a such array:
[ [ [ 3, 3, 5 ],
[ 4, 3, 3 ] ],
[ [ 3, 2, 3 ],
[ 0, 3, 8 ] ] ]
I would like to do so without flatten the array.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
遵循 sepp2k 的想法,这里是一个可能的实现:
然后根据需要在数组上应用 deep_map:
或者,更简单地说:
或者,多态地:
Following sepp2k idea, here is a possible implementation:
Then apply deep_map as you wish on the array:
Or, more briefly:
Or, polymorphically:
您可以编写一个
deep_map
方法,该方法在数组上调用map
,然后针对每个元素测试它是否是子数组。如果是,则使用子数组递归调用deep_map,否则产生该元素。然后,您可以使用该
deep_map
方法来转换多维数组的内部元素,而不影响其结构。You can write a
deep_map
method, which callsmap
on the array and then for each element test whether it's a sub-array. If it is, calldeep_map
recursively with the sub-array, otherwise yield the element.You can then use that
deep_map
method to transform the inner elements of your multi-dimensional array without affecting its structure.因此,如果我做得正确,
f(x)
将遍历多维数组,直到找到一个包含非 数组 或 子类的内容的数组。 >Array,此时它将生成块最里面的Array,并将其替换为块的返回值。So, if I've done this right,
f(x)
will traverse a multidimensional Array until it finds one containing something that isn't an Array or subclass of Array, at which point it will yield the innermost Array to the block and replace it with the block's return value.