Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Avoid hitting ArgumentError for parsing integers and floats. #98

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
39 changes: 31 additions & 8 deletions lib/psych/scalar_scanner.rb
Expand Up @@ -86,26 +86,49 @@ def tokenize string
end
i
when FLOAT
begin
return Float(string.gsub(/[,_]/, ''))
rescue ArgumentError
end
float = parse_float(string)
return float if float

@string_cache[string] = true
string
else
if string.count('.') < 2
begin
return Integer(string.gsub(/[,_]/, ''))
rescue ArgumentError
end
integer = parse_integer(string)
return integer if integer
end

@string_cache[string] = true
string
end
end

###
# Parse a string and attempt to return an integer, or nil if unparsable.
def parse_integer(string)
subbed_string = string.gsub(/[,_]/, '')
integer = subbed_string.to_i

# if result is zero, confirm there's no non-zero characters
return integer if integer != 0 || /^0+$/.match(subbed_string)

nil
end

###
# Parse a string and attempt to return an integer, or nil if unparsable.
def parse_float(string)
# more than one . means it should not be a float
return nil if /\..*\./.match(string)

subbed_string = string.gsub(/[,_]/, '')
float = subbed_string.to_f

# if result is zero, confirm there's no non-zero characters
return float if float != 0.0 || /^0*\.0+$/.match(subbed_string)

nil
end

###
# Parse and return a Time from +string+
def parse_time string
Expand Down