8

I'm new to Ruby, and have been working my way through Mr Neighborly's Humble Little Ruby Guide. There have been a few typos in the code examples along the way, but I've always managed to work out what's wrong and subsequently fix it - until now!

This is really basic, but I can't get the following example to work on Mac OS X (Snow Leopard):

gone = "Got gone fool!"
puts "Original: " + gone
gone.delete!("o", "r-v")
puts "deleted: " + gone

Output I'm expecting is:

Original: Got gone fool!
deleted: G gne fl!

Output I actually get is:

Original: Got gone fool!
deleted: Got gone fool!

The delete! method doesn't seem to have had any effect.

Can anyone shed any light on what's going wrong here? :-\

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Brian
  • 123
  • 1
  • 1
  • 8

3 Answers3

13

The String.delete method (Documented here) treats its arguments as arrays and then deletes characters based upon the intersection of its arrays.

The intersection of 2 arrays is all characters that are common to both arrays. So your original delete of gone.delete!("o", "r-v") would become

gone.delete ['o'] & ['r','s','t','u','v']

There are no characters present in both arrays so the deletion would get an empty array, hence no characters are deleted.

Steve Weet
  • 28,126
  • 11
  • 70
  • 86
  • Another typo chalked up to the examples in the book then. ;-) Thanks a lot for the explanation. – Brian Apr 25 '10 at 17:52
2

I changed

gone.delete!("o", "r-v")

to

gone.delete!("or-v")

and it works fine.

Sid Heroor
  • 663
  • 4
  • 11
  • Thanks a lot! I tried just about everything but that! Out of interest, are you on MAC OS X, too? – Brian Apr 25 '10 at 08:13
  • Nope. I use ruby on windows and linux. Most of ruby should be OS agnostic and so any initial problems you face shouldn't be specific to OS X. – Sid Heroor Apr 26 '10 at 02:25
  • Careful about expansion when using double quotes : http://stackoverflow.com/a/4190812/1729094 – yPhil Oct 22 '15 at 18:26
1

You get same o/p using some different way like gsub

puts "deleted: " + gone.gsub('o', '')

o/p

deleted: Got gone fool!
Salil
  • 46,566
  • 21
  • 122
  • 156