在Ruby中更优雅的方式来做到这一点

时间:2009-12-21 12:54:57

标签: ruby syntax

我开始使用Ruby,并且每天都在寻找新的,更短,更优雅的方法来编写代码。

在解决Project Euler问题时,我写了很多像

这样的代码
if best_score < current_score
  best_score = current_score
end

有更优雅的方式来写这个吗?

8 个答案:

答案 0 :(得分:16)

best_score = [best_score, current_score].max

参见:Enumerable。max


免责声明:虽然这有点可读性(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

将导致(使用ruby 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)

答案 1 :(得分:15)

这可以在一行上完成:

best_score = current_score if best_score < current_score

答案 2 :(得分:6)

也许是一个单行?

best_score = current_score if best_score < current_score

答案 3 :(得分:2)

这很优雅。它易读且易于维护。

如果你想要更短,你可以去:

best_score = current_score if best_score < current_score

best_score = current_score unless best_score >= current_score

......但在所有情况下都不一定是改进(请记住可读性)。

答案 4 :(得分:1)

由于我无法在上面看到它,所以我倾向于使用ternary operator

best_score = current_score > best_score ? current_score : best_score

并且还有这种不太常见的版本:

best_score = (best_score > current_score && best_score) || current_score

...这更难以阅读,但显示(对我而言)短暂的意外副作用。 (见this blog post。)

答案 5 :(得分:0)

不确定它是否符合“更优雅”的条件,但如果您不想每次都重写if ...

def max(b,c)
 if (b < c)
  c
 else
  b
 end
end

best = 10 
current = 20
best = max(best,current)

答案 6 :(得分:0)

或者这样

(current_score > best_score) ? best_score = current_score : best_score

答案 7 :(得分:0)

它看起来很好你已经拥有它的方式。我只会改变比较,所以它写道:

如果当前得分大于最佳得分

您也可以创建一个方法并调用它。这对我来说更为OO。

 def get_best_score() 
      current_score > best_score ?
          current_score :
          best_score
 end

这是OOP的全部意义吗?保持对象状态。

best_score = get_best_score()
相关问题