在块中分配变量

时间:2012-10-12 12:35:51

标签: ruby architecture

我想每个人都遇到过这样的代码:

def query(sql)
  logger.debug "Db: Executing query #{sql}"
  result = nil
  ts = Benchmark.realtime do
    result = @db.exec sql
  end
  logger.debug "Db: Query completed in #{ts}"
  result
end

坦率地说,这看起来很难看。是否有更优雅的方式来实现相同的结果?

1 个答案:

答案 0 :(得分:2)

您可以编写自己的包装方法,如下所示,并隐藏丑陋:

require 'benchmark'

def bm (description, &block)
  [].tap do |result|
  ts = Benchmark.realtime do
    result <<  block.call
  end
    p "#{description} completed in #{ts}"
  end.first
end

result =  bm("db query") {"db result"}
p result 

输出:

"db query completed in 5.131e-06"
"db result"