Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strip method for non-whitespace characters?

Is there a Ruby/Rails function that will strip a string of a certain user-defined character? For example if I wanted to strip my string of quotation marks "... text... "

http://api.rubyonrails.org/classes/ActiveSupport/Multibyte/Chars.html#M000942

like image 876
alamodey Avatar asked Mar 29 '09 09:03

alamodey


2 Answers

You can use tr with the second argument as a blank string. For example:

%("... text... ").tr('"', '')

would remove all the double quotes.

Although if you are using this function to sanitize your input or output then it will probably not be effective at preventing SQL injection or Cross Site Scripting attacks. For HTML you are better off using the gem sanitize or the view helper function h.

like image 44
toothygoose Avatar answered Oct 07 '22 09:10

toothygoose


I don't know if I'm reinventing the wheel here so if you find a built-in method that does the same, please let me know :-)

I added the following to config/initializers/string.rb , which add the trim, ltrim and rtrim methods to the String class.

# in config/initializers/string.rb
class String
  def trim(str=nil)
    return self.ltrim(str).rtrim(str)
  end

  def ltrim(str=nil)
    if (!str)
      return self.lstrip
    else
      escape = Regexp.escape(str)
    end

    return self.gsub(/^#{escape}+/, "")
  end

  def rtrim(str=nil)
    if (!str)
      return self.rstrip
    else
      escape = Regexp.escape(str)
    end

    return self.gsub(/#{escape}+$/, "")
  end
end

and I use it like this:

"... hello ...".trim(".") => " hello "

and

"\"hello\"".trim("\"") => "hello"

I hope this helps :-)

like image 123
Abdo Avatar answered Oct 07 '22 07:10

Abdo