[英]Ruby, run all methods
是否可以運行和輸出所有方法? 不確定如何通過點運算符傳遞符號。 因此,應該不是link.:node
而是應該是link.node
require 'mechanize'
agent = Mechanize.new
page = agent.get("http://stackoverflow.com/")
link = page.link
p meth = link.methods #=> [:node, :href, :attributes, :page, :referer, :click, :dom_id, :dom_class, :pretty_print, :inspect, :rel, :rel?, :noreferrer?, :text, :to_s, :uri, :pretty_print_cycle, :pretty_print_instance_variables, :pretty_print_inspect, :nil?, :===, :=~, :!~, :eql?, :hash, :<=>, :class, :singleton_class, :clone, :dup, :initialize_dup, :initialize_clone, :taint, :tainted?, :untaint, :untrust, :untrusted?, :trust, :freeze, :frozen?, :methods, :singleton_methods, :protected_methods, :private_methods, :public_methods, :instance_variables, :instance_variable_get, :instance_variable_set, :instance_variable_defined?, :instance_of?, :kind_of?, :is_a?, :tap, :send, :public_send, :respond_to?, :respond_to_missing?, :extend, :display, :method, :public_method, :define_singleton_method, :object_id, :to_enum, :enum_for, :pretty_inspect, :==, :equal?, :!, :!=, :instance_eval, :instance_exec, :__send__, :__id__]
#this doesn't work.
meth.each do |x|
puts "#{x}: #{link.x}"
end
如果要訪問該類的方法,可以使用以下方法
調用私有方法
meth.each { |x| puts "#{x}: #{link.class.send(x)}" }
調用公共方法
meth.each { |x| puts "#{x}: #{link.send(x)}" }
用參數或參數調用方法
meth.each { |x| puts "#{x}: #{link.class.send(x, params_or_arguments)}" }
meth.each { |x| puts "#{x}: #{link.send(x, params_or_arguments)}" }
您可以使用send
,但是正如注釋中所指出的那樣,許多方法都會產生錯誤的含義:
meth.each { |x| puts "#{x}: #{link.send(x)}" }
順便說一句:如果您想學習Ruby,我寫了一篇對您來說可能很有趣的寶石: methodfinder
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.