What's the opposite of append in Ruby? <<

ruby

Solution

Why can't I just do this?: a >> 'bar' - This would be super-duper!

Because it's much clearer to use `[]`.

a = 'foobar'
a['bar'] = ''
a # 'foo'

If you need to match only `bar` at the end, use a regular expression:

a = 'barfoobar'
a[/bar$/] = ''
a # 'barfoo'

`a >> 'bar'` wouldn't be 'super duper', it would be totally ambiguous. What does `a >> b` mean? Are you popping a character off the end and storing it in `b`, or taking the value of `b` off the end of `a`, or converting both sides to integers and bit-shifting? `<<` denotes movement, the characters from the right-hand side are moving to the left. `>>` would suggest to me that characters are moving from left to right, not that I want to remove and discard characters from the left.

The only reason `a << 'foo'` works is because appending to a string is one of the most common things you'll ever do in software.

Problem

If `a = 'foo'` I can do `a << 'bar'` and get back `foobar` But say I want to remove `bar`? I know I can do `a.slice!(3..a.length)` - But damn is that ugly. So let's `regex` this silly bastard like: `a.gsub!('bar','')` - But is this the best method? Why can't I just do this?: `a >> 'bar'` - This would be super-duper! So how do you guys do it? What is the fastest method?

Original source