2009-12-21 225 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