2yo1lq
Last Updated: February 25, 2016
·
327
· karunamon

Enumerable ranges from strings in Ruby

A snippet that I find myself using quite a bit. This monkey-patches the String class with a to_r method, giving you a Range that can be called with enumerators. Since this uses eval, it accepts numbers only for security.

class String
  def to_r
    a = self.partition(/\(.*?\)/)
    fail "No range in string" if a[0].empty?
    fail "Invalid range #{a}" if a.select { |v| v.match(/[A-Za-z]/) }
    eval a[1]
  end

  def to_r_leading_zero
    a = self.partition(/\(.*?\)/)
    fail "No range in string" if a[0].empty?
    fail "Invalid range #{a}" if a.select { |v| v.match(/[A-Za-z]/) }
    r = eval a[1]
    if r.first.to_s.size == 1
      eval "\'#{"0" + r.first.to_s}\'..\'#{r.last.to_s}\'"
    end
  end
end