eval in Ruby

今天把之前做的一个工具集成到我的一个工具框架中,结果遇到了问题。我的工具和框架都是用ruby写的,框架通过eval方法调用注册的工具。而我的工具中有一个对于Array的monkey patch。
class Array do
alias old_zip zip
def zip(another_array)
if another_array and another_array.size > size
(another_array.size-size).times{ self << nil }
end

old_zip(another_array)
end
end


我单独运行工具的时候,一切正常。但是,集成之后却报一个错:module Tools.Methods.Array 没有方法zip。

原来是我在一个自定义的module中调用的eval.而传入的string就是我的那个工具原文件,这样看来,monkey patch没有找到Array这样一个类。所以也就无法找到一个zip方法。
我把代码改成这样就好了:
Array.class_eval do
alias old_zip zip
def zip(another_array)
if another_array and another_array.size > size
(another_array.size-size).times{ self << nil }
end

old_zip(another_array)
end
end
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值