ceth
ceth

Reputation: 45325

Remove substring from the string

I am just wondering if there is any method to remove string from another string? Something like this:

class String
  def remove(s)
    self[s.length, self.length - s.length]
  end
end

Upvotes: 235

Views: 331865

Answers (9)

Igor Drozdov
Igor Drozdov

Reputation: 15055

Ruby 2.5+

If your substring is at the beginning of in the end of a string, then Ruby 2.5 has introduced the methods for this:

  • delete_prefix for removing a substring from the beginning of the string
  • delete_suffix for removing a substring from the end of the string

Upvotes: 64

Pete
Pete

Reputation: 18085

You can use the slice method:

a = "foobar"
a.slice! "foo"
=> "foo"
a
=> "bar"

there is a non '!' version as well. More info can be seen in the documentation about other versions as well: http://www.ruby-doc.org/core/classes/String.html#method-i-slice-21

Upvotes: 292

Dinatih
Dinatih

Reputation: 2476

If you are using rails or at less activesupport you got String#remove and String#remove! method

def remove!(*patterns)
  patterns.each do |pattern|
    gsub! pattern, ""
  end

  self
end

source: http://api.rubyonrails.org/classes/String.html#method-i-remove

Upvotes: 4

Claudio Floreani
Claudio Floreani

Reputation: 2571

If I'm interpreting right, this question seems to ask for something like a minus (-) operation between strings, i.e. the opposite of the built-in plus (+) operation (concatenation).

Unlike the previous answers, I'm trying to define such an operation that must obey the property:

IF c = a + b THEN c - a = b AND c - b = a

We need only three built-in Ruby methods to achieve this:

'abracadabra'.partition('abra').values_at(0,2).join == 'cadabra'.

I won't explain how it works because it can be easily understood running one method at a time.

Here is a proof of concept code:

# minus_string.rb
class String
  def -(str)
    partition(str).values_at(0,2).join
  end
end

# Add the following code and issue 'ruby minus_string.rb' in the console to test
require 'minitest/autorun'

class MinusString_Test < MiniTest::Test

  A,B,C='abra','cadabra','abracadabra'

  def test_C_eq_A_plus_B
    assert C == A + B
  end

  def test_C_minus_A_eq_B
    assert C - A == B
  end

  def test_C_minus_B_eq_A
    assert C - B == A
  end

end

One last word of advice if you're using a recent Ruby version (>= 2.0): use Refinements instead of monkey-patching String like in the previous example.

It is as easy as:

module MinusString
  refine String do
    def -(str)
      partition(str).values_at(0,2).join
    end
  end
end

and add using MinusString before the blocks where you need it.

Upvotes: 2

edwardmp
edwardmp

Reputation: 6611

If you are using Rails there's also remove.

E.g. "Testmessage".remove("message") yields "Test".

Warning: this method removes all occurrences

Upvotes: 42

JayTarka
JayTarka

Reputation: 571

here's what I'd do

2.2.1 :015 > class String; def remove!(start_index, end_index) (end_index - start_index + 1).times{ self.slice! start_index }; self end; end;
2.2.1 :016 >   "idliketodeleteHEREallthewaytoHEREplease".remove! 14, 32
 => "idliketodeleteplease" 
2.2.1 :017 > ":)".remove! 1,1
 => ":" 
2.2.1 :018 > "ohnoe!".remove! 2,4
 => "oh!" 

Formatted on multiple lines:

class String
    def remove!(start_index, end_index)
        (end_index - start_index + 1).times{ self.slice! start_index }
        self
    end 
end

Upvotes: -2

Waiting for Dev...
Waiting for Dev...

Reputation: 13037

If it is a the end of the string, you can also use chomp:

"hello".chomp("llo")     #=> "he"

Upvotes: 132

the Tin Man
the Tin Man

Reputation: 160621

If you only have one occurrence of the target string you can use:

str[target] = ''

or

str.sub(target, '')

If you have multiple occurrences of target use:

str.gsub(target, '')

For instance:

asdf = 'foo bar'
asdf['bar'] = ''
asdf #=> "foo "

asdf = 'foo bar'
asdf.sub('bar', '') #=> "foo "
asdf = asdf + asdf #=> "foo barfoo bar"
asdf.gsub('bar', '') #=> "foo foo "

If you need to do in-place substitutions use the "!" versions of gsub! and sub!.

Upvotes: 57

Piyush Mattoo
Piyush Mattoo

Reputation: 16153

How about str.gsub("subString", "") Check out the Ruby Doc

Upvotes: 192

Related Questions