Declaring an integer Range with step != 1 in Ruby

后端 未结 3 1659
感情败类
感情败类 2020-12-17 15:09

UPDATE 2: For posterity, this is how I\'ve settled on doing it (thanks to Jorg\'s input):

100.step(2, -2) do |x|
    # my code
end
         


        
3条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-17 15:31

    I had similar issue here are the various ways I found to do the same SIMPLE thing I used step in the end because it allowed for NEGATIVE and FRACTIONAL increments and I had no conditions, other than the bounds to look for

      case loop_type
    
        when FOR
          # doen't appear to have a negative or larger than 1 step size!
          for kg in 50..120 do
            kg_to_stones_lbs(kg)
          end
    
        when STEP
          120.step(70,-0.5){ |kg|
            kg_to_stones_lbs(kg)
          }
    
        when UPTO
          50.upto(120) { |kg|
            kg_to_stones_lbs(kg)
          }
    
        when DOWNTO
          120.downto(50){ |kg|
            kg_to_stones_lbs(kg)
          }
    
        when RANGE
          (50..120).reverse_each{ |kg|
            kg_to_stones_lbs(kg)
          }
    
        when WHILE
          kg = 120
          while kg >= 50
            kg_to_stones_lbs(kg)
            kg -= 0.5
          end
      end
    

    O/P:

    92.0kg - 14st 7lbs

    91.5kg - 14st 6lbs

    91.0kg - 14st 5lbs

    90.5kg - 14st 4lbs

    90.0kg - 14st 2lbs

    89.5kg - 14st 1lbs

    89.0kg - 14st 0lbs

    88.5kg - 13st 13lbs

    88.0kg - 13st 12lbs

提交回复
热议问题