/me@(voip.)?|www./ SamLown.com

Ruby: Handling fixed string lengths and UTF-8

Until Ruby 1.9 is supported by your favorite plugins and gems, proper UTF-8 support in your ruby code is a serious challenge. If, like me, you don’t have time to wait, the following really simple code snippet should help you to at least fix the sprintf problem of fixing the lengths of strings with unicode characters.


  # UTF-8 safe operations for setting a string width
  # Aligns to left by default and pads with spaces. Options include:
  #
  #   :align => :left (default), :right
  #   :pad => ' '
  #
  def string_to_width(string, width, options = {})
    options.reverse_merge!(
      :pad => ' ', :align => :left
    )
    new_string = ""
    i = 0
    string.each_char do |c|
      break if i == width
      new_string += c
      i += 1
    end
    # add padding
    if new_string.jlength < width
      padding = (options[:pad] * (width - new_string.jlength))
      new_string = options[:align] == :left ?
        new_string + padding : padding + new_string
    end
    new_string
  end

I place that in my application_helper.rb and ensure require 'jcode' is included in the Rails environment.rb file.

written by Sam,


No comments yet


Write your comment



HTML will be removed, but Textile formating is permitted. Log in for your comment to be posted without review.