2009-12-21 232 views
8

我已经开始使用Ruby,并且正在寻找新的,简短的,优雅的方式来编写代码。Ruby中更优雅的方式

在解决项目欧拉的问题,我已经写了很多代码像

if best_score < current_score 
    best_score = current_score 
end 

有没有写这个更优雅的方式?

best_score = current_score if best_score < current_score 
+1

+1对于http://projecteuler.net/ – miku 2009-12-21 13:30:28

+3

+1对于在Ruby中做项目欧罗尔 – akuhn 2009-12-21 15:14:20

+0

希望你现在满意我们的投票状态吗? ;) – CoffeeCode 2010-03-12 08:38:52

回答

16
best_score = [best_score, current_score].max 

见:枚举。 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 

将导致(与红宝石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) 
+4

这是用蝙蝠扑打苍蝇,不是吗? – guns 2009-12-21 13:32:11

+2

这个解决方案的好处是数组可以包含任意数量的元素。 – Geo 2009-12-21 13:40:40

+1

感谢您的基准。 Enumerable的max方法看起来不错,但当我像问题50交叉时,我可能不得不在最后切换到条件:) – Anurag 2009-12-21 23:06:23

15

这可以在一个单一的线来完成?

best_score = current_score if best_score < current_score 
+1

把条件放在声明的末尾是光辉的。 – Anurag 2009-12-21 22:56:17

6

也许一个班轮:

+0

作为一个领导,这与Trevor的答案相同。 – 2012-04-30 22:14:23

0

不知道这将有资格作为“更优雅”,但是如果你不希望如果每次重写......

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

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

-1他不想交换变量。重读这个问题。 – Tomas 2009-12-21 13:54:33

+0

@Tomas:'swap'在这里是一个用词不当的人。 'max'对于函数实际*会做些什么更为恰当的描述。 – mipadi 2009-12-21 17:08:22

+0

上帝,我讨厌当我想念明显。谢谢;) – phtrivier 2009-12-22 17:51:43

2

这是不够优雅。它易读易维护。

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

best_score = current_score if best_score < current_score 

best_score = current_score unless best_score >= current_score 

...但它不一定在所有情况下的改善(记住可读性)。

0

还是这样

(current_score > best_score) ? best_score = current_score : best_score 
0

它看起来很好,你已经拥有它。

如果目前的得分大于最好成绩

您还可以创建一个方法,并调用:所以它读取我只会改变比较。对我来说更是OO。

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

这是OOP的全部内容吗?保持对象状态。

best_score = get_best_score() 
+0

如果我们谈论优雅,best_score = get_best_score会更好。或者只是分数= best_score – marcgg 2009-12-21 14:07:34

+0

既然你在捕获变量,为什么不去一个lambda呢? – Geo 2009-12-21 17:17:26

+1

我更喜欢面向对象和更少功能 – OscarRyz 2009-12-21 18:32:32

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。)

+1

这是一个不错的职位..应该不是表达式? best_score =(best_score> current_score && best_score)|| current_score – Anurag 2009-12-21 23:35:33

+0

@Auurag - 是的,应该,谢谢。测试用例不足!我会解决它。 – 2009-12-22 10:35:50