Ads

 

How to remove the first character of a ruby string

Recently, I had to remove the first character of string in a private nanoc-powered project. I easily found a quick and elegant way to achieve this and according to this stackoverflow answer it seems the fastest.

  path="_theString"
  path[1..-1]  # => "theString"

And to complete this post, if you plan to use this often, you may want to override the String class to remove the first n characters :
  
class String
  def removeFirstChars!(how_many = 1)
    self.replace self[how_many..-1]
  end
end

The stackoverflow answer also gives the code and benchmark results to achieve this with an Array.

Comments

Ads