newBike
newBike

Reputation: 15002

How to write method in exclamation way, modified on itself not returns the modified copy

I want to make the change on the original string object, how to ?

Now, it only returns the copy.

class String
  def clean_text!
    self.delete("\n").gsub!(/\s/,'')
  end
  def add_sig!
    self + "add sig"
  end
end

Upvotes: 0

Views: 49

Answers (1)

konsolebox
konsolebox

Reputation: 75498

Try this:

self.delete!("\n")
self.gsub!(/\s/,'')
self

Also, newlines are already included in \s so no need to have self.delete!("\n"). Simply do

class String
  def clean_text!
    self.gsub!(/\s/,'')
    self
  end
end

For add_sig, use << instead of +:

  def add_sig!
    self << "add sig"
  end

Upvotes: 4

Related Questions