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

Fix handle empty string in String#to_f(whitespace: false) #14902

Merged
merged 2 commits into from
Aug 16, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions spec/std/string_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -321,6 +321,7 @@ describe "String" do
it { expect_raises(ArgumentError) { "1__234".to_i } }
it { expect_raises(ArgumentError) { "1_234".to_i } }
it { expect_raises(ArgumentError) { " 1234 ".to_i(whitespace: false) } }
it { expect_raises(ArgumentError) { "".to_i(whitespace: false) } }
it { expect_raises(ArgumentError) { "0x123".to_i } }
it { expect_raises(ArgumentError) { "0b123".to_i } }
it { expect_raises(ArgumentError) { "000b123".to_i(prefix: true) } }
Expand Down Expand Up @@ -515,6 +516,7 @@ describe "String" do
"nan".to_f?(whitespace: false).try(&.nan?).should be_true
" nan".to_f?(whitespace: false).should be_nil
"nan ".to_f?(whitespace: false).should be_nil
expect_raises(ArgumentError) { "".to_f(whitespace: false) }
"nani".to_f?(strict: true).should be_nil
" INF".to_f?.should eq Float64::INFINITY
"INF".to_f?.should eq Float64::INFINITY
Expand Down
3 changes: 2 additions & 1 deletion src/string.cr
Original file line number Diff line number Diff line change
Expand Up @@ -752,7 +752,8 @@ class String
end

private def to_f_impl(whitespace : Bool = true, strict : Bool = true, &)
return unless whitespace || '0' <= self[0] <= '9' || self[0].in?('-', '+', 'i', 'I', 'n', 'N')
return unless first_char = self[0]?
return unless whitespace || '0' <= first_char <= '9' || first_char.in?('-', '+', 'i', 'I', 'n', 'N')

v, endptr = yield

Expand Down
Loading