Strip first character using Ruby

It’s easy enough to remove the last character of a string in Ruby, but what about the first? Probably the neatest way for a simple script is to just extend the String class by monkey patching it with two new method thus:

class String
  def chopfirst

  def chopfirst!
    return self

The first returns the newly shortened string, but doesn’t modify it, the second returns it an modifies it. Note that because slice normally returns the sliced character I’ve added an extra return line to avoid possibly confusing return values.

You can then just use this as a method on any string, ie

var = 'abcd'
puts var     #=> abcd

puts var     #=> abcd

puts var.chopfirst  #=> bcd

puts var     #=> bcd

Written on 19 Sep 2009 and categorised in Ruby, tagged as string and class

Home, Post archive

site copyright Eric Freeman

Valid XHTML 1.0 Strict