Skip to content

Instantly share code, notes, and snippets.

@vraravam
Created January 13, 2016 03:03
Show Gist options
  • Save vraravam/c241c057eb8dfbc7d926 to your computer and use it in GitHub Desktop.
Save vraravam/c241c057eb8dfbc7d926 to your computer and use it in GitHub Desktop.
string to unicode conversion in ruby
# config/initializers/string.rb
class String
# TODO: Don't know how to convert to UTF-16BE encoding using built-in methods, and then arrive
# at the result similar to: http://api.mvaayoo.com/unicodeutil/unicode.jsp
def to_unicode
unpack('U*').map { |i| i.to_s(16).rjust(4, '0') }.join
end
end
@Yegorov
Copy link

Yegorov commented Feb 7, 2025

Other solution, use codepoints method.
And first need convert string to UTF-8 or UTF-16BE.

class String
  def to_unicode
    encode('UTF-8').codepoints.map { _1.to_s(16).rjust(4, '0') }.join
  end
end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment