From 73ad15103019f94b789a3b0f13209a0a988df584 Mon Sep 17 00:00:00 2001 From: Pavel Pravosud Date: Fri, 24 Oct 2014 13:25:55 -0400 Subject: Make `String#remove` and `String#remove!` accept multiple arguments --- activesupport/CHANGELOG.md | 4 ++++ .../lib/active_support/core_ext/string/filters.rb | 16 ++++++++++------ activesupport/test/core_ext/string_ext_test.rb | 14 ++++++++++++-- 3 files changed, 26 insertions(+), 8 deletions(-) diff --git a/activesupport/CHANGELOG.md b/activesupport/CHANGELOG.md index f9df972929..0c90549826 100644 --- a/activesupport/CHANGELOG.md +++ b/activesupport/CHANGELOG.md @@ -1,3 +1,7 @@ +* `String#remove` and `String#remove!` accept multiple arguments. + + *Pavel Pravosud* + * Corrected Inflector#underscore handling of multiple successive acroynms. *James Le Cuirot* diff --git a/activesupport/lib/active_support/core_ext/string/filters.rb b/activesupport/lib/active_support/core_ext/string/filters.rb index 2b1583d4ac..499b9b26bc 100644 --- a/activesupport/lib/active_support/core_ext/string/filters.rb +++ b/activesupport/lib/active_support/core_ext/string/filters.rb @@ -20,14 +20,18 @@ class String self end - # Returns a new string with all occurrences of the pattern removed. Short-hand for String#gsub(pattern, ''). - def remove(pattern) - gsub pattern, '' + # Returns a new string with all occurrences of the patterns removed. + def remove(*patterns) + dup.remove!(*patterns) end - # Alters the string by removing all occurrences of the pattern. Short-hand for String#gsub!(pattern, ''). - def remove!(pattern) - gsub! pattern, '' + # Alters the string by removing all occurrences of the patterns. + def remove!(*patterns) + patterns.each do |pattern| + gsub! pattern, "" + end + + self end # Truncates a given +text+ after a given length if +text+ is longer than length: diff --git a/activesupport/test/core_ext/string_ext_test.rb b/activesupport/test/core_ext/string_ext_test.rb index 2f4691817f..35095f2b2d 100644 --- a/activesupport/test/core_ext/string_ext_test.rb +++ b/activesupport/test/core_ext/string_ext_test.rb @@ -260,8 +260,18 @@ class StringInflectionsTest < ActiveSupport::TestCase end def test_remove - assert_equal "Summer", "Fast Summer".remove(/Fast /) - assert_equal "Summer", "Fast Summer".remove!(/Fast /) + original = "This is a good day to die" + assert_equal "This is a good day", original.remove(" to die") + assert_equal "This is a good day", original.remove(" to ", /die/) + assert_equal "This is a good day to die", original + end + + def test_remove! + original = "This is a very good day to die" + assert_equal "This is a good day to die", original.remove!(" very") + assert_equal "This is a good day to die", original + assert_equal "This is a good day", original.remove!(" to ", /die/) + assert_equal "This is a good day", original end def test_constantize -- cgit v1.2.3