代码之家  ›  专栏  ›  技术社区  ›  bennybdbc

如何在Ruby中从不同的类中调用对象的方法?

  •  0
  • bennybdbc  · 技术社区  · 16 年前

    对不起,这个问题的措辞,我真的不知道该怎么说。我的意思是,我该怎么做:

    class Test
      def doSomething
        puts "I'm working"
      end
    end
    
    class numberTwo
      def doSomethingElse
        subject.doSomething
        puts "Doing other things"
      end
    end
    subject = Test.new
    otherObject = numberTwo.new
    otherObject.doSomethingElse
    

    提前谢谢。

    6 回复  |  直到 16 年前
        1
  •  1
  •   Derek    16 年前

    如果希望一个类中的方法了解另一个类的实例(在调用“new”时创建实例,并将其分配给变量,如subject),则该变量需要

    a) 正如格伦·麦克唐纳(glenn mcdonald)建议您使用$subject所指出的那样,要全球化。$表示一个全局变量

    b) 成为调用的类的成员,因此不会在类之外创建调用。所以subject将是NumberTwo的成员变量,并且可能在NumberTwo的构造函数中初始化

    c) 可以作为参数传入。

    在我看来,考虑到您向我们展示的内容,最简单的方法是将subject作为参数传入。

    class NumberTwo
      def doSomethingElse(subject)
         subject.doSomething
      end
    end
    
    subject = Test.new
    otherObject = numberTwo.new
    otherObject.doSomethingElse(subject)
    
        2
  •  1
  •   DigitalRoss    16 年前

    • 提供对NumberTwo#initialize或某些其他属性编写器的引用
    • 使用全局变量保存引用

    除了工厂方法之外,已经有很多例子了,所以我会做一个。。。

    class NumberTwo
      def doSomethingElse
        @myTest.doSomething
        puts "Doing other things"
      end
      def testFactory
        @myTest = Test.new
      end
    end
    otherObject = NumberTwo.new
    subject = otherObject.testFactory
    otherObject.doSomethingElse
    
        3
  •  0
  •   Jorge Israel Peña    16 年前

    我不确定这是否是您的意思,但您可以创建一个类方法:

    class Test
      def self.doSomething
        puts "I'm working"
      end
    end
    

    subject.doSomething 线路应该是 Test.doSomething .

        4
  •  0
  •   glenn mcdonald    16 年前

    将“主题”更改为“$subject”,您就可以开始了。

        5
  •  0
  •   JRL    16 年前

    如果希望一个类调用另一个类的成员,则必须使该类成为第一个类的成员,或从该类派生。

    numberTwo 类尝试对其没有引用的对象(主题)调用方法。

        6
  •  0
  •   jtbandes    16 年前

    otherObject 对象需要某种方法来了解 something 对象方法声明的作用域阻止类了解 创建方法时。这里有一个可能的解决方案:

    class Foo
      def doSomething
        puts "I'm working"
      end
    end
    class Bar
      attr_accessor :foo
      def doSomethingElse
        foo.doSomething unless foo.nil?
        puts "Doing other things"
      end
    end
    foo = Foo.new
    bar = Bar.new
    bar.foo = foo
    bar.doSomethingElse
    
    推荐文章