From efa2299ac3bbf86feacfa337645654f87109e769 Mon Sep 17 00:00:00 2001 From: Kasper Timm Hansen Date: Fri, 26 Jul 2019 22:00:56 +0200 Subject: Remove tough to grasp -1 + 1 = 0 from String#to In case a negative position is provided that exceeds the size of the string, we're relying on -1 returned from max to get 0 length by + 1 and let [] with a 0 length returning "" for us. E.g. "hello".to(-7), where -7 + 5 size = -2. That's lower than -1, so we use -1 instead and + 1 would turn it into 0. Instead allow outer bounds access and always return "". --- activesupport/lib/active_support/core_ext/string/access.rb | 4 ++-- activesupport/test/core_ext/string_ext_test.rb | 2 ++ 2 files changed, 4 insertions(+), 2 deletions(-) (limited to 'activesupport') diff --git a/activesupport/lib/active_support/core_ext/string/access.rb b/activesupport/lib/active_support/core_ext/string/access.rb index 4894193665..4f70e7f5fc 100644 --- a/activesupport/lib/active_support/core_ext/string/access.rb +++ b/activesupport/lib/active_support/core_ext/string/access.rb @@ -61,8 +61,8 @@ class String # str.from(0).to(-1) # => "hello" # str.from(1).to(-2) # => "ell" def to(position) - position = [position + length, -1].max if position < 0 - self[0, position + 1] + position += size if position < 0 + self[0, position + 1].to_s end # Returns the first character. If a limit is supplied, returns a substring diff --git a/activesupport/test/core_ext/string_ext_test.rb b/activesupport/test/core_ext/string_ext_test.rb index c5a000b67a..b1ab9533e7 100644 --- a/activesupport/test/core_ext/string_ext_test.rb +++ b/activesupport/test/core_ext/string_ext_test.rb @@ -455,6 +455,8 @@ class StringAccessTest < ActiveSupport::TestCase test "#to with negative Integer, position is counted from the end" do assert_equal "hell", "hello".to(-2) + assert_equal "h", "hello".to(-5) + assert_equal "", "hello".to(-7) end test "#from and #to can be combined" do -- cgit v1.2.3