我已經開始使用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