2011-08-10 55 views
1

如何提取任意對象的所有成員(方法,變量,常量,對象等)並將它們傳遞給塊?Ruby:提取對象的所有成員

def inside(obj) 
    #pass all the members of the object to the block 
end 

inside myLink do 
    url = "myurl.com" 
end 

回答

2

您可以使用instance_eval的:

def inside obj, &block 
    obj.instance_eval &block 
end 

你仍然需要使用,雖然自:

inside myLink do 
    self.url = "myurl.com" 
    # or: 
    @url = "myurl.com" 
end 
+0

嗯,我仍然不知道是否有可能使我提出的語法我的OP。 – themirror

+0

不在Ruby中,OP中的代碼將創建一個名爲「url」的本地變量,併爲其分配「myurl.com」。它不會影響傳入對象的實例變量@url。 – robbrit