Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Adding UTF8 methods to class String in Ruby (See related posts)

From: http://redhanded.hobix.com/inspect/nikolaiSUtf8LibIsAllReady.html (in the comments)
Requirement: sudo gem install character-encodings --remote

For the module Encoding::Character::UTF8::Methods see the file called utf-8.rb
in the source code of character-encodings.



require('encoding/character/utf-8')

class Proc

  def uStringMethods()
    umethods = []
    Encoding::Character::UTF8.methods.each do |m|    
      umethods.push(%!
          define_method("u#{m}") do |*args|
            Encoding::Character::UTF8.#{m}(self, *args)
          end  # unless instance_methods.include?("u#{m}")
        !)
    end

    #puts umethods
    umethods = umethods.reject { |m| m =~ /taguri/ }

    String.class_eval(umethods.join)
  end

end


Proc.new {}.uStringMethods()     #  adds methods defined in module Encoding::Character::UTF8::Methods to class String


puts "caf\303\251".length      #=>  5
puts "caf\303\251".ulength     #=>  4


#puts String.public_methods.select { |x| x =~ /^u/ }.sort
#puts String.new.public_methods.select { |x| x =~ /^u/ }.sort



You need to create an account or log in to post comments to this site.


Click here to browse all 5141 code snippets

Related Posts