Created
October 1, 2012 20:38
-
-
Save takehiko/3814274 to your computer and use it in GitHub Desktop.
Numerical Character References
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env ruby | |
# -*- coding: utf-8 -*- | |
# Numerical Character References | |
if RUBY_VERSION < "1.9" | |
$KCODE = "u" | |
class String | |
def ord | |
self[0] | |
end | |
end | |
end | |
require "optparse" | |
module Ncr | |
module_function | |
def get_ref(param, opt = {}) | |
code = 0 | |
ch = "" | |
case param | |
when /^[1-9]/ | |
ch = $& | |
num = ch.to_i | |
code = 9311 + num | |
when /^0/ | |
ch = $& | |
code = 0x24ea | |
when /^heart/i | |
ch = $& | |
code = 0x2665 | |
when /^jis/i | |
ch = $& | |
code = 0x3004 | |
when /^[a-z]/ | |
ch = $& | |
code = 0x24d0 + (ch.ord - ?a.ord) | |
end | |
opt[:ch] = ch | |
code_to_s(code, opt) | |
end | |
def code_to_s(code, opt = {}) | |
str = (opt[:hex] ? "&\#x%x;" : "&\#%d;") % code | |
if opt[:output] != :short | |
str += " ... #{opt[:ch]}" | |
end | |
if opt[:output] == :html | |
str += "<br>" | |
end | |
str | |
end | |
end | |
if __FILE__ == $0 | |
op = OptionParser.new | |
h = {} | |
op.on("-x", "--hexadecimal", "hexadecimal") { | |
h[:hex] = true | |
} | |
op.on("-s", "--short", "values only") { | |
h[:output] = :short | |
} | |
op.on("-h", "--html", "HTML") { | |
h[:output] = :html | |
} | |
op.parse!(ARGV) | |
if ARGV.empty? | |
argv = ["1"] | |
else | |
argv = ARGV | |
end | |
argv.each do |param| | |
puts Ncr.get_ref(param, h) | |
end | |
end | |
# Example | |
# ruby ncr.rb | |
# ruby ncr.rb -x 1 | |
# ruby ncr.rb -s 1 | |
# ruby ncr.rb -xh 1 2 3 4 5 heart jis a b c x y z |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment