Skip to content

Instantly share code, notes, and snippets.

@adam12
Created March 30, 2022 16:57
Show Gist options
  • Save adam12/68491a792a7e28f1e8c69197cd475caa to your computer and use it in GitHub Desktop.
Save adam12/68491a792a7e28f1e8c69197cd475caa to your computer and use it in GitHub Desktop.
require "minitest/autorun"
require "strscan"
class Scanner < StringScanner
def between(left, right, occurence)
# StringScanner expects Regexp instances
left = Regexp.new(left)
right = Regexp.new(right)
# Skip ahead until we're in the right area
occurence.times do
skip_until(left)
end
# I'd probably want to improve this
val = ""
until eos? do
break if check(right)
val += getch
end
# Reset incase we want to re-use this scanner
reset
val
end
end
class TestScanner < Minitest::Test
def test_between
scanner = Scanner.new("this-is-a-string-to-scan")
assert_equal "is", scanner.between("-", "-", 1)
assert_equal "string", scanner.between("-", "-", 3)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment