2013-03-26 2 views
1

테스트 컨텍스트에서 배열의 특정 비율을 취해야합니다. 루비에서이 문제를 해결하는 가장 좋은 방법입니다루비, 배열의 특정 요소 백분율을 취하는 방법

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 

: 내 요청의

사양이 테스트에서 설명 될 수 있는가?

답변

6

내가 쓰는 것 :

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

나는 이런 라이너를 좋아합니다. +1. – Linuxios

+1

또는'take (size * percent/100.0) .ceil' –

+1

몇 가지 제안 된 변경 사항이 적용되었습니다. 나는 괄호를 쓰는 것을 선호한다 (DSL 구조를 쓰지 않는 한) – tokland

0

내 실제 접근 방식은 이것이다 :

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

이 당신이 찾고있는 사람인가? 그 대답을 얻었습니까? –

+0

리뷰로서 나는 다음과 같이 말하고 싶습니다. 1) 명백한 '자기'를 쓰지 마십시오. 2) '길이'/ '크기'가 이미 있기 때문에 '전체'를 만들 필요가 없습니다. 3)'100.to_f' ->'100.0'. 4)'self [0, elements]'->'take (elements)'. 5)이 메소드가'Array'에 충분히 추가 될 수 있는지를 논쟁의 여지가 있습니다. – tokland

+0

@iAmRubuuu 이것이 나의 첫 번째 접근 방식이었습니다. 나는 받아 들인 대답으로 더 많은 뷰티 솔루션을 찾고있었습니다. – fguillen

관련 문제