Created
February 28, 2019 16:25
-
-
Save pankuznetsov/4ffa58aa124c1c3e8d654efe9c1c9870 to your computer and use it in GitHub Desktop.
Code for paring string
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$code = '' # Line for execution | |
$base = 0 # Master pointer, points the place where functions start parsing | |
def peek(oft) # Returns symbol from $code by index oft relatively to the $base | |
if oft < 0 or oft >= $code.size then return nil end | |
return $code[$base + oft] | |
end | |
def skip_trash # Function skipping whitespaces. | |
i = 0 # The pointer | |
while $base + i < $code.size and peek(i).match?(/\s/) do # Skipping until it gets non-space character | |
i += 1 | |
end | |
$base += i | |
return i | |
end | |
def parse_string # Returns string content between double quotes | |
i = 1 # 1 casue I need to skip first double quote, otherwise it will be treated as last double quote by following while cycle | |
str = '' # The actual string content | |
while $base + i < $code.size and peek(i) != '"' do # Iterate while current character is not double quote | |
# Checking for EOF - End Of File | |
if $base + i >= $code.size - 1 then | |
raise 'Unexpected EOF: " was Expected' | |
return nil | |
end | |
str += peek(i) # Adding new characted to the string | |
i += 1 # Moving pointer i to next character | |
end | |
$base += str.size + 2 | |
skip_trash # I call skip_trash in order for elimenate spaces and tabs after parsing the string | |
# So, the idea is to make parsing functions skip spaces and tabs | |
return str | |
end | |
# Example of usage | |
$code = '"ABCDEF"' | |
$base = 0 | |
puts "string parsed: #{parse_string}" # Prints out: string parsed: ABCDEF |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment