aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--activesupport/CHANGELOG.md5
-rw-r--r--activesupport/lib/active_support/multibyte/chars.rb7
-rw-r--r--activesupport/test/multibyte_chars_test.rb8
3 files changed, 18 insertions, 2 deletions
diff --git a/activesupport/CHANGELOG.md b/activesupport/CHANGELOG.md
index c02c5a82f5..e5d945bb42 100644
--- a/activesupport/CHANGELOG.md
+++ b/activesupport/CHANGELOG.md
@@ -1,3 +1,8 @@
+* Update `ActiveSupport::Multibyte::Chars#slice!` to return `nil` if the
+ arguments are out of bounds, to mirror the behavior of `String#slice!`
+
+ *Gourav Tiwari*
+
* Fix `number_to_human` so that 999999999 rounds to "1 Billion" instead of
"1000 Million".
diff --git a/activesupport/lib/active_support/multibyte/chars.rb b/activesupport/lib/active_support/multibyte/chars.rb
index a76692ec4b..707cf200b5 100644
--- a/activesupport/lib/active_support/multibyte/chars.rb
+++ b/activesupport/lib/active_support/multibyte/chars.rb
@@ -86,7 +86,8 @@ module ActiveSupport #:nodoc:
end
# Works like <tt>String#slice!</tt>, but returns an instance of
- # Chars, or nil if the string was not modified.
+ # Chars, or nil if the string was not modified. The string will not be
+ # modified if the range given is out of bounds
#
# string = 'Welcome'
# string.mb_chars.slice!(3) # => #<ActiveSupport::Multibyte::Chars:0x000000038109b8 @wrapped_string="c">
@@ -95,7 +96,9 @@ module ActiveSupport #:nodoc:
# string # => 'me'
def slice!(*args)
string_sliced = @wrapped_string.slice!(*args)
- string_sliced ? chars(string_sliced) : nil
+ if string_sliced
+ chars(string_sliced)
+ end
end
# Reverses all characters in the string.
diff --git a/activesupport/test/multibyte_chars_test.rb b/activesupport/test/multibyte_chars_test.rb
index 42829c6a8e..8d4d9d736c 100644
--- a/activesupport/test/multibyte_chars_test.rb
+++ b/activesupport/test/multibyte_chars_test.rb
@@ -423,6 +423,14 @@ class MultibyteCharsUTF8BehaviourTest < ActiveSupport::TestCase
assert_equal 'ù', chars
end
+ def test_slice_bang_returns_nil_and_does_not_modify_receiver_if_out_of_bounds
+ string = 'úüù'
+ chars = string.mb_chars
+ assert_nil chars.slice!(4, 5)
+ assert_equal 'úüù', chars
+ assert_equal 'úüù', string
+ end
+
def test_slice_should_throw_exceptions_on_invalid_arguments
assert_raise(TypeError) { @chars.slice(2..3, 1) }
assert_raise(TypeError) { @chars.slice(1, 2..3) }