临时变量太多的解决方案

用链式调用替换临时变量

before

class MovieQue
  
  def movies
    @movies ||= []
  end
  
  def add_movie(title)
    movies << title
  end
end
  
rental = MovieQue.new
rental.add_movie("Shawshank Redemption")
rental.add_movie("Flight of the Navigator")
rental.add_movie("Happy Gilmore")

after

class MovieQue
  def self.with_movie(title)
    rental = self.new
    rental.movies << title
    rental
  end
 
  def movies
    @movies ||= []
  end
 
  def and(title)
    movies << title
    self
  end
end

抽到方法里面

参考

chain

你可能感兴趣的:(临时变量太多的解决方案)