Is there a way of changing regular expressions to a range of numbers in Ruby on Rails?

后端 未结 2 783
离开以前
离开以前 2021-01-27 17:04

I often need to create range of numbers in regular expressions. So e.g. \'[2-3][0-9]\' is range of numbers between 20-39. To double check my range, I normally use Linux command.

2条回答
  •  难免孤独
    2021-01-27 17:57

    You should write a unit test if you're concerned about it.

    To test your regex quickly, use irb and write plain old Ruby:

    irb(main):005:0> (1..40).map(&:to_s).grep(/[2-3][0-9]/)
    => ["20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31", "32", "33", "34", "35", "36", "37", "38", "39"]
    

    That said, there are far better ways of producing ranges of numbers than filtering a whole sequence through a regular expression. That might, in fact, be the worst way of doing so.

    (20..39).to_a
    

    or

    20.upto(39).to_a
    

    or

    20.times.map { |i| 20 + i }
    

    And many, many, many more. They're all infinitely better than using a regex to filter down a larger set of numbers to only those you need in order to build a simple sequential range.

提交回复
热议问题