我是一個(gè)測試員,,呵呵,最近使用ruby實(shí)現(xiàn)automation test時(shí)需要將一個(gè)class及其方法配置在一個(gè)xml中,這樣一來我就需要實(shí)現(xiàn)動態(tài)調(diào)用class.即像java中的forName方法一樣,可以將字符型的類名及方法名轉(zhuǎn)成類和方法.找了一段時(shí)間終于查到,原來是用const_get 和send方法,現(xiàn)分享一下,請看示例:
class Klass
def hello(word)
return word
end
end
className='Klass'
methodName='hello'
param1='word'
k=Kernel.const_get(className).new()
if k.respond_to?(methodName)
puts k.send(methodName,param1)
end