Skip to content

Instantly share code, notes, and snippets.

@Stormwind
Last active December 10, 2015 01:38
Show Gist options
  • Save Stormwind/4360816 to your computer and use it in GitHub Desktop.
Save Stormwind/4360816 to your computer and use it in GitHub Desktop.
gsub seems to replace the original encoding of the give sting with the encoding of the gsub content.
foo = 'fo'
foo.force_encoding('UTF-8')
puts foo.encoding.inspect # #<Encoding:UTF-8>
foo2 = foo.gsub(/o/) { |bar| 195.chr }
puts foo2.inspect # "f\xC3"
puts foo2.length.inspect # 2
puts foo2.encoding.inspect # #<Encoding:ASCII-8BIT>
# encoding: UTF-8
foo = 'föo'
foo.force_encoding('UTF-8')
puts foo.encoding.inspect # #<Encoding:UTF-8>
# breakes here
foo2 = foo.gsub(/o/) { |bar| "Русский".force_encoding("iso-8859-5") }
# never reached
puts foo2
puts foo2.inspect
puts foo2.length.inspect
puts foo2.encoding.inspect
# encoding: UTF-8
foo = "Русский".force_encoding("iso-8859-5")
puts foo.encoding.inspect # #<Encoding:ISO-8859-5>
# breakes here
foo2 = foo.gsub(/с/) { |bar| "föö".force_encoding("UTF-8") }
# never reached
puts foo2
puts foo2.inspect
puts foo2.length.inspect
puts foo2.encoding.inspect
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment