The ruby strip() method

Ruby’s strip() method is useful for stripping extra spaces in strings. Unfortunately, you cannot use strip() method to remove non-space characters from a string.

The following method can strip non-space characters from a string as well.

def strip(str,char)
   new_str = ""
   str.each_byte do |byte|
      new_str << byte.chr unless byte.chr == char
   end
   new_str
end
Example: strip('Hello World','o') #=> Hell Wrld
About these ads

About this entry