views:

59

answers:

3

in Python, we can e.g.

"[foo ]".strip(" []") # -> "foo"

how do we do this in Ruby? string strip method is stripping only whitespace ..

UPDATE

stripping is not deleting! : )

"[ foo boo  ]".strip(" []") # -> "foo boo"
A: 

Try the gsub method:

irb(main):001:0> "[foo ]".gsub(/\As+[/,'')
=> "foo ]"

irb(main):001:0> "foo ]".gsub(/s+]\Z/,'')
=> "foo"

etc.

Peter
This, like all the other answers, removes all occurrences of the given characters. The OP only wants to remove the occurrences at either end of the string (like strip, but not only for whitespace).
sepp2k
Whoops, thought ^ matched the start of the string. Changed.
Peter
@Peter: I didn't actually see the ^ (which might be because it was in front of the opening `/` instead of behind it). But `\A` is more correct, yes. +1
sepp2k
Try this on `[ [] foo [] boo [][]] `. Your regexes will return the string unchanged because they rely on a particular order of the characters. Also, there's a `\\` missing.
Tim Pietzcker
@Tim From my understanding of the OP requirements returning ``[] foo [] boo [][]`` for your example would be correct behaviour.
Peter
No, in Python `"[ [] foo [] boo [][]] ".strip(" []")` returns `"foo [] boo"`.
Tim Pietzcker
+4  A: 

There is no such method in ruby, but you can easily define it like:

def my_strip(string, chars)
  chars = Regexp.escape(chars)
  string.gsub(/\A[#{chars}]+|[#{chars}]+\Z/, "")
end

my_strip " [la[]la] ", " []"
#=> "la[]la"
sepp2k
*There is no such method in ruby* .. this is honest, thanks :)
mykhal
+1: I like this. It also looks like `#{chars}` automagically escapes regex metacharacters - is that right? If it were just string substitution, the regex shouldn't work in your example. However, you might want to use `\A` and `\Z` instead of `^` and `$` - the latter ones will also match around newlines which might not be desired.
Tim Pietzcker
@Tim: `#{}` doesn't escape - that's why I have the call to Regexp.escape in there. Good point about \A and \Z.
sepp2k
Oh. My fault - (wer lesen kann, ist klar im Vorteil).
Tim Pietzcker
+1  A: 
"[[ ] foo [] boo ][ ]".gsub(/\A[ \[\]]+|[ \[\]]+\Z/,'') 
=> "foo [] boo"

Can also be shortenend to

"[[ ] foo [] boo ][ ]".gsub(/\A[][ ]+|[][ ]+\Z/,'') 
=> "foo [] boo"
Tim Pietzcker