/examples/string-sub-gsub.rb
Ruby | 12 lines | 9 code | 0 blank | 3 comment | 0 complexity | f2c29b738c0f6d1bcb7fa365b1e74870 MD5 | raw file
- alphabet = [*?a..?f].join
- alphabet.sub(/U/, 'you?') #=> "abcdef"
- alphabet.gsub(/[b-e]/){|match| "<U+#{'%.4X' % match.ord}>"}
- #=> "a<U+0062><U+0063><U+0064><U+0065>f"
- alphabet.sub!(?V, 'for Vendetta') #=> nil
- '3 + -4'.sub(/(?<a>\d+) \+ -(?<b>\d+)/,
- "== \\k<a> - \\k<b>")
- #=> "== 3 - 4"
- subs = {?& => '&', ?> => '>'}
- subs.default = '?'
- 'You & I > he & they!'.gsub(/[[:punct:]]/, subs)
- #=> "You & I > he & they?"