Performs ‘dollar substitution’ on a piece of text with a given dictionary.
require 'rubygems'
require 'rufus/dollar'
h = {
"name" => "Fred Brooke",
"title" => "Silver Bullet"
}
puts Rufus::Dollar.dsub "${name} wrote '${title}'", h
# => "Fred Brooke wrote 'Silver Bullet'"
puts Rufus::Dollar.dsub "${name} wrote ${title}", h
# => "Fred Brooke wrote Silver Bullet"
puts Rufus::Dollar.dsub "${name} wrote ${'title}", h
# => 'Fred Brooke wrote "Silver Bullet"'
# File lib/rufus/dollar.rb, line 63
63: def self.dsub(text, dict, offset=nil)
64:
65: text = text.to_s
66:
67: j = text.index('}', offset || 0)
68:
69: return text unless j
70:
71: t = text[0, j]
72:
73: i = t.rindex('${')
74: ii = t.rindex("\\${")
75:
76: iii = t.rindex('{')
77: iii = nil if offset
78:
79: return text unless i
80: return dsub(text, dict, j+1) if (iii) and (iii-1 > i)
81:
82: return unescape(text) if (i) and (i != 0) and (ii == i-1)
83: #
84: # found "\${"
85:
86: key = text[i+2..j-1]
87: quote = false
88:
89: if m = key.match(/^['"](.+)$/)
90: key = m[1]
91: quote = true
92: end
93:
94: value = dict[key]
95: value = value.nil? ? '' : value.to_s
96: value = value.inspect if quote
97:
98: pre = (i > 0) ? text[0..i-1] : ''
99:
100: dsub("#{pre}#{value}#{text[j+1..-1]}", dict)
101: end
Disabled; run with --debug to generate this.
Generated with the Darkfish Rdoc Generator 1.1.6.