如何在Ruby中只执行一次方法?有静态变量吗?

bas*_*ibe 5 ruby static

我写了一个脚本,其中包含一些方法定义,没有类和一些公共代码.其中一些方法执行一些非常耗时的shell程序.但是,这些shell程序只需在第一次调用方法时执行.

现在在C中,我将在每个方法中声明一个静态变量,以确保这些程序只执行一次.我怎么能用Ruby做到这一点?

Ars*_*en7 10

红宝石有一个成语:x ||= y.

def something
  @something ||= calculate_something
end

private

def calculate_something
  # some long process
end
Run Code Online (Sandbox Code Playgroud)

但是,如果您的"长时间运行的实用程序"可能返回错误值(false或nil),则此问题存在问题,因为||=运算符仍将导致对右侧进行评估.如果您期望错误的值,那么使用一个额外的变量,方式类似于DigitalRoss的建议:

def something
  return @something if @something_calculated
  @something = calculate_something
  @something_calculated = true
  return @something
end
Run Code Online (Sandbox Code Playgroud)

不要先尝试保存一行代码,先设置@something_calculated变量,然后再运行calculate_something.如果您的计算函数引发异常,则您的函数将始终返回nil并且永远不会再次调用计算.

更一般地说,在Ruby中,您使用实例变量.但请注意,它们在给定对象的所有方法中都是可见的 - 它们不是方法的本地方法.如果需要所有实例共享的变量,请在类对象和每个实例调用中定义方法self.class.something

class User
  def self.something
    @something ||= calculate_something
  end

  def self.calculate_something
    # ....
  end

  def something
    self.class.something
  end
end
Run Code Online (Sandbox Code Playgroud)