简体   繁体   中英

Ruby, run all methods

Is it possible to run and output all the methods? Not sure how to pass symbols through the dot operator. So instead of link.:node it should be 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

If you want to access method of the class, you can use the following ways

To call private methods

meth.each { |x| puts "#{x}: #{link.class.send(x)}" }

To call public methods

meth.each { |x| puts "#{x}: #{link.send(x)}" }

To call methods with arguments or params

meth.each { |x| puts "#{x}: #{link.class.send(x, params_or_arguments)}" }
meth.each { |x| puts "#{x}: #{link.send(x, params_or_arguments)}" }

You can use send , but as pointed out in the comments, a lot of methods will have the wrong arity:

meth.each { |x| puts "#{x}: #{link.send(x)}" }

BTW: if you are trying to learn Ruby, I wrote a gem that might be interesting for you: methodfinder

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM