Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ruby

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?

like image 683
MrPizzaFace Avatar asked Nov 01 '25 01:11

MrPizzaFace


1 Answers

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.

like image 164
meagar Avatar answered Nov 03 '25 16:11

meagar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!