是否可以从Rails控制台中猴子修补阵列类?当我尝试运行以下代码时,出现此错误。
class Array
def push(obj)
return
end
end
我收到以下错误
ArgumentError: wrong number of arguments (given 5, expected 1)
from (pry):2:in `push'
答案 0 :(得分:4)
Rails控制台本身似乎正在使用Array#push
,并且在定义后将使用猴子补丁版本。
push
的标准版本被定义为接受传递给它的参数,但是您的替换版本仅接受单个参数obj
,因此不兼容。
这会导致您提到的wrong number of arguments (given 5, expected 1)
错误。
要将push
替换为兼容版本,您可以使用Ruby的*
("splat" operator)定义可以接受任意数量参数的方法:
def push(*obj)
# implementation here
end
用不做任何事情就返回的方法替换push
可能会引起很多问题。也许用有关您要执行的操作的更多详细信息来更新问题。