2013-03-26 59 views
1

在測試環境中,我需要獲取數組元素的特定百分比。Ruby,如何獲取數組元素的特定百分比

def test_percent_elements 
    array = [1,2,3,4,5,6,7,8,9,10] 

    assert_equal([], array.percent_elements(0)) 
    assert_equal([1], array.percent_elements(1)) 
    assert_equal([1], array.percent_elements(10)) 
    assert_equal([1,2], array.percent_elements(11)) 
    assert_equal([1,2,3,4,5], array.percent_elements(50)) 
    assert_equal([1,2,3,4,5,6,7,8,9,10], array.percent_elements(100)) 
end 

這是Ruby來解決這個問題的最好辦法:

我的要求的規格能夠在這個測試來說明?

回答

6

我會寫:

class Array 
    def percent_elements(percent) 
    take((size * percent/100.0).ceil) 
    end 
end 
+0

我喜歡這樣的襯衫。 +1。 – Linuxios 2013-03-26 16:39:39

+1

或'take(size * percent/100.0).ceil' – 2013-03-26 16:40:35

+1

應用一些建議的更改。我更喜歡把parens(除非寫一些DSL結構) – tokland 2013-03-26 16:42:47

0

我的實際做法是這樣的:

class Array 
    def percent_elements(percent) 
    total = self.length 
    elements = ((total * percent)/100.to_f).ceil 
    self[0, elements] 
    end 
end 
+0

這是你要找的人?意味着你是否得到了答案? – 2013-03-26 16:31:56

+0

作爲一個審查,我會說:1)不要寫明確的'self's。 2)由於'length' /'size'已經存在,因此不需要創建'total'。 3)'100.to_f' - >'100.0'。 4)'self [0,elements]' - >'take(elements)'。 5)這個方法是否足夠通用以被添加到'Array'是有爭議的。 – tokland 2013-03-26 16:51:26

+0

@iAmRubuuu這是我的第一個方法,我正在尋找更多的美容解決方案作爲接受的答案。 – fguillen 2013-03-27 09:53:54