首页 > 解决方案 > 如何优化 Ruby 方法

问题描述

我有一个红宝石方法

def get_status(creds)
  client = create_client(creds)
  status = client.account_status
  client.close_session
  status
end

tap通常,我通过or优化这种代码yield_self,但在这里我找不到优化它的好方法。

我想出的唯一解决方案:

def get_status(creds)
  create_client(creds).yeild_self do |client|
    [client, client.account_status]
  end.yield_self do |client, status|
    client.close_session
    status
  end
end

但它并不比原来的解决方案更好,是吗?

标签: ruby

解决方案


可以写如下。

class Client
  def account_status
    "Overdrawn!"
  end
  def close_session
    puts "It's closed"
  end
end
def create_client(creds)
  Client.new
end    
def get_status(creds)
  begin
    client = create_client(creds)
    client.account_status
  ensure
    client.close_session if client
  end
end
get_status("Anything")
It's closed
  #=> "Overdrawn!"

我更喜欢这个问题而不是问题中的#1吗?不。

我更喜欢这个问题而不是问题中的#2吗?是的!

我更喜欢@max的答案吗?不。


我知道可以使用类方法ObjectSpace::define_finalizer创建终结器。

class Client
  def initialize
    ObjectSpace.define_finalizer(self, proc { puts "It's finalized!" })
  end

  def account_status
    "Overdrawn!"
  end
end
def create_client(creds)
  Client.new
end    
def get_status(creds)
  create_client(creds).account_status
end
get_status("Anything")
  #=> "Overdrawn!" 
exit
It's finalized!

在创建终结器时必须小心,如此处所述。我了解有时使用的一种技术是让finalizerproc 引用类级对象。例如,请参阅这篇文章、@Amadan 下面的评论和@Matt 对这个问题的评论。我不提倡使用终结器。我只是认为不熟悉终结器的读者(就像我在写这篇文章之前一样)会发现这很有用。


推荐阅读