Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove a character at an index position in Ruby

Tags:

ruby

Basically what the question says. How can I delete a character at a given index position in a string? The String class doesn't seem to have any methods to do this.

If I have a string "HELLO" I want the output to be this

["ELLO", "HLLO", "HELO", "HELO", "HELL"]

I do that using

d = Array.new(c.length){|i| c.slice(0, i)+c.slice(i+1, c.length)}

I dont know if using slice! will work here, because it will modify the original string, right?

like image 284
Maulin Avatar asked Oct 22 '09 18:10

Maulin


People also ask

How do I remove a specific character 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 I use Delete in Ruby?

Ruby | Set delete() function The delete() is an inbuilt method in Ruby which deletes the given object from the set and returns the self object. In case the object is not present, it returns self only. Parameters: The function takes a mandatory parameter object which is to be deleted.

How do you cut a string in Ruby?

split is a String class method in Ruby which is used to split the given string into an array of substrings based on a pattern specified. Here the pattern can be a Regular Expression or a string. If pattern is a Regular Expression or a string, str is divided where the pattern matches.

How do you delete the first character in Ruby?

The chr method removes the first character of a string in Ruby. It removes the one-character string at the beginning of a string and returns this character.


2 Answers

If you're using Ruby 1.8, you can use delete_at (mixed in from Enumerable), otherwise in 1.9 you can use slice!.

Example:

mystring = "hello"
mystring.slice!(1)  # mystring is now "hllo"
# now do something with mystring
like image 110
JRL Avatar answered Oct 21 '22 16:10

JRL


Won't Str.slice! do it? From ruby-doc.org:

str.slice!(fixnum) => fixnum or nil [...]

 Deletes the specified portion from str, and returns the portion deleted.
like image 20
Berry Avatar answered Oct 21 '22 14:10

Berry