当前位置: 动力学知识库 > 问答 > 编程问答 >

Remove a character at an index position in 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?

网友答案:
$ 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"
网友答案:

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.
网友答案:

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
网友答案:

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?

分享给朋友:
您可能感兴趣的文章:
随机阅读: