繁体   English   中英

Ruby,运行所有方法

[英]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.

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