Non so se sto reinventare la ruota qui quindi se si trova un metodo incorporato che fa lo stesso, fatemelo sapere :-)
ho aggiunto il testo seguente config/initializers/string.rb
, che aggiungere i metodi trim
, ltrim
e rtrim
alla classe 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
e lo uso come questo:
"... hello ...".trim(".")
=> "ciao"
e
"\"hello\"".trim("\"")
=> "ciao"
Spero che questo aiuta :-)
Ma voglio solo sostituire "all'inizio e alla fine del mio strin g/testo. – alamodey