Declaring an integer Range with step != 1 in Ruby

后端 未结 3 1640
感情败类
感情败类 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条回答
  • 2020-12-17 15:22

    You can't declare a Range with a "step". Ranges don't have steps, they simply have a beginning and an end.

    You can certainly iterate over a Range in steps, for example like this:

    (2..100).step(2).reverse_each(&method(:p))
    

    But if all you want is to iterate, then what do you need the Range for in the first place? Why not just iterate?

    100.step(2, -2, &method(:p))
    

    This has the added benefit that unlike reverse_each it does not need to generate an intermediate array.

    0 讨论(0)
  • 2020-12-17 15:29

    This question answers yours: about ruby range?

    (2..100).step(2) do |x|
        # your code
    end
    
    0 讨论(0)
  • 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

    0 讨论(0)
提交回复
热议问题