2013-03-30 13 views
12

mogę iteracyjne jak tenJak mogę powtórzyć odwrócony zakres z określonym krokiem w Ruby?

(0..10).step(2){|v| puts v} 

ale ponieważ odwróconą zakres wynosi pustym przedziale, nie mogę iteracyjne tędy

(10..0).step(2){|v| puts v} 

będzie zarobić mi nic. Oczywiście, mogę iteracyjne w tył jak to

10.downto(0){|v| puts v} 

ale downto metoda nie pozwala mi ustawić inne kroki oprócz domyślnie 1. To coś bardzo proste, więc przypuszczam, że nie powinno być wbudowany w sposób zrób to, czego nie wiem.

+0

można zrobić coś takiego '(0..10) .step (2) .reverse' ale możesz potrzebować dodać trochę logiki na wypadek, gdyby rzekomy wynik z '(10..0) .step (2)' był inny. – jvnill

+0

'(0..10) .step (2) .reverse' jest nieprawidłowe; Ruby mówi: 'NoMethodError: undefined method 'reverse' dla # '. –

Odpowiedz

20

Dlaczego nie używacie Numeric#step:

Od docs:

Invokes block with the sequence of numbers starting at num, incremented by step (default 1) on each call. The loop finishes when the value to be passed to the block is greater than limit (if step is positive) or less than limit (if step is negative). If all the arguments are integers, the loop operates using an integer counter. If any of the arguments are floating point numbers, all are converted to floats, and the loop is executed floor(n + n*epsilon)+ 1 times, where n = (limit - num)/step. Otherwise, the loop starts at num, uses either the < or > operator to compare the counter against limit, and increments itself using the + operator.

 
irb(main):001:0> 10.step(0, -2) { |i| puts i } 
10 
8 
6 
4 
2 
0 
+1

Nice. Znalazłem też inny sposób, mniej elegancki: (-10..0) .step (2) {| v | stawia -1 * v} – user1887348

4

Bardzo łatwo jest emulować step, pomijając wartości, których nie potrzebujesz. Coś takiego:

10.downto(0).each_with_index do |x, idx| 
    next if idx % 3 != 0 # every third element 
    puts x 
end 
# >> 10 
# >> 7 
# >> 4 
# >> 1 
+0

Jeśli warunkowo pomijasz elementy w każdym stwierdzeniu, robisz to źle i powinno używać się opcji: '10.downto (0) .select.with_index {| x, idx | idx% 3 == 0} .each {| x | umieszcza x} ' – SamStephens

+0

@SamStephens: to jest dyskusyjne. –

+0

Wszystko jest, ale powiem, że jeśli zamierzasz używać funkcji Ruby w oparciu o funkcje funkcjonalne, powinieneś używać ich konsekwentnie, zamiast mieszać style funkcjonalne i imperatywne. – SamStephens

Powiązane problemy