在 def 中初始化变量和在普通方法中这样做的区别

Difference between initializing variables in def and doing so in normal method

假设我有两个 类 比如:

class Abc
  def initialize(arg1, arg2)
    @a = arg1
    @b = arg2
  end

  def sum
    return @a+@b
  end
end

obj = Abc.new(2, 3)
obj.add # => 5

class Abc1
  def sum(arg1, arg2)
    return arg1+arg2
  end
end

obj = Abc1.new
obj.sum(2,3) # =>5

在两个 类 中,我调用一个 sum 方法并得到 5 作为结果。哪种方法更好,为什么?

这取决于用例。如果变量要在对象上的其他方法调用之间共享,那么将它们初始化为实例变量是有意义的。如果它们仅用于特定方法调用,则应将它们作为方法参数传递。

所以两者都可能是正确的,但在您的特定代码中,第二个 (Abc1) 没有(太多)意义,因为在 sum 的方法调用中,没有什么特别的Abc1 实例用于执行。作为 class 方法是有意义的:

class Abc1
  def self.sum(arg1, arg2)
    arg1 + arg2
  end
end

Abc1.sum(2,3) # =>5