Delete character at index position in Ruby

Basically what this question says. How can I delete a character at a given index position in a string? The String class does not seem to have methods for this.

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

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

I use

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

I don’t know if I use a slice! will work here because it will change the original line, right?

+4
source share
5 answers
 $ 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" 
+2
source

There will be no Str.slice! do this? From ruby-doc.org:

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

  Deletes the specified portion from str, and returns the portion deleted. 
+9
source

If you are using Ruby 1.8, you can use delete_at (mixed 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 
+4
source

I did something like this

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

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

+1
source

To avoid the need for a Monkey String patch, you can use tap :

 "abc".tap {|s| s.slice!(2) } => "ab" 

If you need to leave the original string unchanged, use dup , for example. abc.dup.tap .

0
source

All Articles