删除Ruby中索引位置的字符

前端之家收集整理的这篇文章主要介绍了删除Ruby中索引位置的字符前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
基本上问题是什么.如何删除字符串中给定索引位置的字符? String类似乎没有任何方法可以执行此操作.

如果我有一个字符串“HELLO”我希望输出是这样的

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

我这样做

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

我不知道是否使用切片!会在这里工作,因为它会修改原始字符串,对吗?

解决方法

  1. $cat m.rb
  2. class String
  3. def maulin! n
  4. slice! n
  5. self
  6. end
  7. def maulin n
  8. dup.maulin! n
  9. end
  10. end
  11. $irb
  12. >> require 'm'
  13. => true
  14. >> s = 'hello'
  15. => "hello"
  16. >> s.maulin(2)
  17. => "helo"
  18. >> s
  19. => "hello"
  20. >> s.maulin!(1)
  21. => "hllo"
  22. >> s
  23. => "hllo"

猜你在找的Ruby相关文章