views:

652

answers:

3

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

+2  A: 

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.

toothygoose
But I only want to replace the " at the start and end of my string/text.
alamodey
A: 

You could use String#gsub:

%("... text... ").gsub(/\A"+|"+\Z/,'')
Magnus Holm
A: 

I don't know of one out of the box, but this should do what you want:

class String
  def strip_str(str)
    gsub(/^#{str}|#{str}$/, '')
  end
end

a = '"Hey, there are some extraneous quotes in this here "String"."'
puts a.strip_str('"') # -> Hey, there are some extraneous quotes in this here "String".
Chuck