从另一个类中的函数调用一个类

时间:2015-07-31 07:24:31

标签: ruby-on-rails ruby

我一直在调用另一个类中的函数内的类。我们假设我有一个课程A,其功能为self.Bc

class A
  def self.b
    //does something
  end
  def c
    //does something
  end
end

和另一个班级D

class D
  before_create :x
  def x
    //have to call the class A and its functions here
  end
end

请告诉我如何实现这一点。

2 个答案:

答案 0 :(得分:5)

您直接在类上调用类方法,并且要调用实例方法,您需要创建该类的实例:

Class D
  before_create :x

  def x
    # for a class method
    A.b

    # for an instance method
    a = A.new
    a.c 
  end
end

答案 1 :(得分:2)

A方法b很简单,它是一个类方法,可以直接从该类调用。所以

class D
  def y
    A.b
  end
end

方法c更有趣,因为它是一个实例方法。因此,您需要创建A类的实例,然后调用其方法c。你可以这样做:

class D
  def z
    A.new.c
  end
end

但是,您通常调用实例方法,因为输出由分配给该实例的参数确定。因此,您不必在A的新实例上调用方法c,而是通常希望创建新实例,按所需方式配置它,然后将其传递给D类方法。所以你需要将A实例传递给D方法。你通常会这样做:

class D
  def z(a)
    a.c
  end
end

a = A.new
d = D.new

d.z(a) 
相关问题