如何广场Array类在Ruby中数组的每一个元素? [英] How to square each element of an array in Array class in Ruby?
问题描述
我的code部分如下:
类Array
高清不散!
self.map {|数字| NUM ** 2}
自
结束
结束
当我打电话:
[1,2,3] .square!
我希望得到[1,4,9],而是我得到[1,2,3]。为什么会出现这样的情况?当我打电话:
[1,2,3] {.MAP | NUM | NUM ** 2}
类方法之外,我得到正确的答案。
阵列#地图
- > 的调用由块返回包含值的新数组self.Creates的每个元素的给定块一次
阵列#地图
- > <!EM>调用自的每个元素的给定块一次,更换与块的返回值的元素
块引用>类Array
高清不散!
self.map! {|数字| NUM ** 2}
结束
结束[1,2,3] .square! #=&GT; [1,4,9]Part of my code is as follows:
class Array def square! self.map {|num| num ** 2} self end end
When I call:
[1,2,3].square!
I expect to get [1,4,9], but instead I get [1,2,3]. Why is this the case? When I call:
[1,2,3].map {|num| num ** 2}
outside of the class method, I get the correct answer.
解决方案You have to use
Array#map!
, notArray#map
.
Array#map
-> Invokes the given block once for each element of self.Creates a new array containing the values returned by the block.
Array#map!
-> Invokes the given block once for each element of self, replacing the element with the value returned by the block.
class Array def square! self.map! {|num| num ** 2} end end [1,2,3].square! #=> [1, 4, 9]
这篇关于如何广场Array类在Ruby中数组的每一个元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!