method
translate
v2_2_9 -
Show latest stable
- Class:
REXML::Functions
translate( string, tr1, tr2 )public
This is entirely Mike Stok’s beast
# File lib/rexml/functions.rb, line 234
def Functions::translate( string, tr1, tr2 )
from = string(tr1)
to = string(tr2)
# the map is our translation table.
#
# if a character occurs more than once in the
# from string then we ignore the second &
# subsequent mappings
#
# if a character maps to nil then we delete it
# in the output. This happens if the from
# string is longer than the to string
#
# there's nothing about - or ^ being special in
# http://www.w3.org/TR/xpath#function-translate
# so we don't build ranges or negated classes
map = Hash.new
0.upto(from.length - 1) { |pos|
from_char = from[pos]
unless map.has_key? from_char
map[from_char] =
if pos < to.length
to[pos]
else
nil
end
end
}
if ''.respond_to? :chars
string(string).chars.collect { |c|
if map.has_key? c then map[c] else c end
}.compact.join
else
string(string).unpack('U*').collect { |c|
if map.has_key? c then map[c] else c end
}.compact.pack('U*')
end
end Related methods
- Class methods
- boolean
- ceiling
- compare_language
- concat
- contains
- context=
- count
- false
- floor
- get_namespace
- id
- lang
- last
- local_name
- method_missing
- name
- namespace_context
- namespace_context=
- namespace_uri
- normalize_space
- not
- number
- position
- processing_instruction
- round
- starts_with
- string
- string_length
- string_value
- substring
- substring_after
- substring_before
- sum
- text
- translate
- true
- variables
- variables=