我从Ruby开始,并且每天都在寻找新的,更短,更优雅的方法来编写代码.
在解决Project Euler问题时,我写了很多代码
if best_score < current_score
best_score = current_score
end
Run Code Online (Sandbox Code Playgroud)
是否有更优雅的方式来写这个?
mik*_*iku 16
best_score = [best_score, current_score].max
Run Code Online (Sandbox Code Playgroud)
见:可数.最大
免责声明:虽然这是一个更具可读性(imho),但性能较差:
require 'benchmark'
best_score, current_score, n = 1000, 2000, 100_000
Benchmark.bm do |x|
x.report { n.times do best_score = [best_score, current_score].max end }
x.report { n.times do
best_score = current_score if best_score < current_score
end }
end
Run Code Online (Sandbox Code Playgroud)
将导致(与红宝石1.8.6(2008-08-11 patchlevel 287)):
user system total real
0.160000 0.000000 0.160000 ( 0.160333)
0.030000 0.000000 0.030000 ( 0.030578)
Run Code Online (Sandbox Code Playgroud)
Tre*_*vor 15
这可以在一行上完成:
best_score = current_score if best_score < current_score
Run Code Online (Sandbox Code Playgroud)
也许一个班轮?
best_score = current_score if best_score < current_score
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
507 次 |
| 最近记录: |