[英]Add an 'each' like method to a Ruby class that inherits from Hash
[英]In Ruby how to run each method of an object at a particular level in the hierarchy (not the methods it inherits)?
我正在使用'Twitter'gem, gem doc和github頁面收集推文。 當它根據條件過濾推文時,例如:
client.filter(locations: "-122.75,36.8,-121.75,37.8") do |tweet|
puts tweet.text
end
從流中產生一條tweet
對象;
(rdb:1) tweet.class
Twitter::Tweet
我可以運行tweet.methods
以獲得可用方法列表,但其中包括非特定於tweet api的方法。 它包括來自Object等的方法。由於我想從該對象中提取所有tweet特定信息以查看它,因此有一種方法可以從“實例方法摘要”列表中運行Class:Twitter :: Tweet中的所有方法。和“實例屬性摘要”自動生成,而不必分別調用每個? (我想為這些tweet對象中的所有數據制作一個JSON)
您能否用ruby-“ Twitter :: Tweet”中的oop范式解釋這意味着什么? 這是否意味着tweet對象是Twitter api和Tweet類的一部分?
對於第一個問題:您可以用一種不太明顯的方式來做到這一點。 只需問自己的類方法:
methods = tweet.class.instance_methods(false)
false
參數在這里很重要,它將刪除父類的所有方法。 因此,您可以運行返回列表中的所有方法。 例如:
methods.each{|method_name| tweet.send(method_name)}
對於第二個問題: Twitter
是所有與gem相關的類的主要模塊,它用於不將Twitter僅與Twitter相關的類弄亂全局名稱空間。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.