我已经开始使用Ruby,并且正在寻找新的,简短的,优雅的方式来编写代码。Ruby中更优雅的方式
在解决项目欧拉的问题,我已经写了很多代码像
if best_score < current_score
best_score = current_score
end
有没有写这个更优雅的方式?
best_score = current_score if best_score < current_score
我已经开始使用Ruby,并且正在寻找新的,简短的,优雅的方式来编写代码。Ruby中更优雅的方式
在解决项目欧拉的问题,我已经写了很多代码像
if best_score < current_score
best_score = current_score
end
有没有写这个更优雅的方式?
best_score = current_score if best_score < current_score
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)
这可以在一个单一的线来完成?
best_score = current_score if best_score < current_score
把条件放在声明的末尾是光辉的。 – Anurag 2009-12-21 22:56:17
也许一个班轮:
作为一个领导,这与Trevor的答案相同。 – 2012-04-30 22:14:23
不知道这将有资格作为“更优雅”,但是如果你不希望如果每次重写......
def max(b,c)
if (b < c)
c
else
b
end
end
best = 10
current = 20
best = max(best,current)
这是不够优雅。它易读易维护。
如果你想更短的,你可以去:
best_score = current_score if best_score < current_score
或
best_score = current_score unless best_score >= current_score
...但它不一定在所有情况下的改善(记住可读性)。
还是这样
(current_score > best_score) ? best_score = current_score : best_score
它看起来很好,你已经拥有它。
如果目前的得分大于最好成绩
您还可以创建一个方法,并调用:所以它读取我只会改变比较。对我来说更是OO。
def get_best_score()
current_score > best_score ?
current_score :
best_score
end
这是OOP的全部内容吗?保持对象状态。
best_score = get_best_score()
既然不能看到它上面,我瘦朝着这个使用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。)
这是一个不错的职位..应该不是表达式? best_score =(best_score> current_score && best_score)|| current_score – Anurag 2009-12-21 23:35:33
@Auurag - 是的,应该,谢谢。测试用例不足!我会解决它。 – 2009-12-22 10:35:50
+1对于http://projecteuler.net/ – miku 2009-12-21 13:30:28
+1对于在Ruby中做项目欧罗尔 – akuhn 2009-12-21 15:14:20
希望你现在满意我们的投票状态吗? ;) – CoffeeCode 2010-03-12 08:38:52