Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby delete method (string manipulation)

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? :-\

like image 785
Brian Avatar asked Apr 25 '10 07:04

Brian


People also ask

How do you remove something from a string in Ruby?

In Ruby, we can permanently delete characters from a string by using the string. delete method. It returns a new string with the specified characters removed.

How do you remove the last two characters of a string in Ruby?

The chop method is used to remove the last character of a string in Ruby. If the string ends with \r\n , it will remove both the separators. If an empty string calls this method, then an empty string is returned. We can call the chop method on a string twice.

How do I remove numbers from a string in Ruby?

string. gsub!( /\d+/,"") will remove all numbers from the string.

How do you modify a string in Ruby?

Ruby allows part of a string to be modified through the use of the []= method. To use this method, simply pass through the string of characters to be replaced to the method and assign the new string.


2 Answers

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.

like image 127
Steve Weet Avatar answered Oct 05 '22 16:10

Steve Weet


I changed

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

to

gone.delete!("or-v")

and it works fine.

like image 43
Sid Heroor Avatar answered Oct 05 '22 15:10

Sid Heroor