tags:

views:

175

answers:

4

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?

+4  A: 

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.
Berry
it returns the ascii value of the character. I want whats left of the string to be returned.
Maulin
Then `str.slice!(fixnum); str`.
Chuck
A: 

I did something like this

c.slice(0, i)+c.slice(i+1, c.length)

Where c is the string and i is the index position I want to delete. Is there a better way?

Maulin
slice! will modify the string in place. So just call slice! on your string with the index of the char you want deleted. Don't use the return value.
JRL
+1  A: 

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
JRL
+1  A: 
$ cat m.rb
class String
  def maulin! n
    slice! n
    self
  end
  def maulin n
    dup.maulin! n
  end
end
$ irb
>> require 'm'
=> true
>> s = 'hello'
=> "hello"
>> s.maulin(2)
=> "helo"
>> s
=> "hello"
>> s.maulin!(1)
=> "hllo"
>> s
=> "hllo"
DigitalRoss
Is there any big difference between `self.class.new(self).maulin! n` and `self.dup.maulin! n`?
glenn jackman
i suppse it should just be `dup.maulin! n`, good point
DigitalRoss