Strip method for characters without spaces?

Is there a Ruby / Rails function that will strip a string of a specific custom character? For example, if I wanted to remove my quote string "... text ..."

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

+5
source share
5 answers

You can use tr with the second argument as an empty string. For example:

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

will remove all double quotes.

, , , , SQL Cross Scripting. HTML h.

+2

, , , , , : -)

config/initializers/string.rb, trim, ltrim rtrim String.

# 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

:

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

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

, : -)

+2

, , :

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".
+1

String # gsub:

%("... text... ").gsub(/\A"+|"+\Z/,'')
0
class String
    # Treats str as array of char
  def stripc(str)
    out = self.dup
    while str.each_byte.any?{|c| c == out[0]}
        out.slice! 0
    end
    while str.each_byte.any?{|c| c == out[-1]}
        out.slice! -1
    end
    out
  end
end

Answer Chuck needs signs +if you want to remove all unnecessary instances of his string template. And this will not work if you want to remove any of the character sets that can appear in any order.

For example, if we want the line to end with none of the following: a, b, cinstead of our line fooabacab, we need something stronger like the code above.

0
source

All Articles