简体   繁体   English

ruby中如何调用多个类中的一个方法

[英]How to call a methods in multiple classes in ruby

class One 
  class Two
    class Three 
      def name
        Faker::Name.name
      end 
    end 

    def workflow
      Three.new
    end
  end

  def event
    Two.new
  end

  def id
    Faker::Number.number(4).to_i
  end 
end

I am new to ruby. Can someone help me, how to call all these methods in ruby?我是 ruby 的新手。有人可以帮助我吗,如何在 ruby 中调用所有这些方法?

Is this what you looking for?这是你要找的吗?

one = One.new
two = One::Two.new
three = One::Two::Three.new

three.name
# => "Mr. Dillon Jacobson" 

two.workflow
# => #<One::Two::Three:0x000055b2d9d70be0>

one.event
# => #<One::Two:0x000055b2df4160d0>
one.id
# => 6579413068

Pretty simple to do with instance_methods(false) that will give us all the defined instance methods of a class. We can then just push all the nested objs into an array and iterate over them.使用instance_methods(false)非常简单,它将为我们提供 class 的所有已定义实例方法。然后我们可以将所有嵌套的 objs 推入一个数组并迭代它们。 I'm not too sure on how to get all nested classes.我不太确定如何获取所有嵌套类。 You can however do that with Module.nesting但是,您可以使用Module.nesting来做到这一点

def call_all_methods(obj)
  obj.class.instance_methods(false).each do |m|
    obj.public_send(m)
  end
end

[
  One.new,
  One::Two.new,
  One::Two::Three.new
].each do |obj|
call_all_methods(obj)
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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