# Two strings holding the same text in different encodings. Ruby will not
# guess how to combine them -- unless every byte involved is ASCII.

utf8   = "caf\u{e9}"
latin1 = utf8.encode("ISO-8859-1")
plain  = "menu: "

def attempt(code)
  result = yield
  puts "  #{code.ljust(22)} #{result.inspect}, #{result.encoding}"
rescue Encoding::CompatibilityError => e
  puts "  #{code.ljust(22)} #{e.class}: #{e.message}"
end

puts "utf8   holds #{utf8.bytesize} bytes, #{utf8.encoding}"
puts "latin1 holds #{latin1.bytesize} bytes, #{latin1.encoding}, the same four characters"
puts "plain  is ASCII only: ascii_only? #{plain.ascii_only?}"
puts
puts "Joining:"
attempt("utf8 + latin1") { utf8 + latin1 }
attempt('"#{utf8} #{latin1}"') { "#{utf8} #{latin1}" }
attempt("plain + latin1") { plain + latin1 }
attempt("plain + utf8") { plain + utf8 }
puts
puts "Asking first:"
puts "  Encoding.compatible?(utf8, latin1)   #{Encoding.compatible?(utf8, latin1).inspect}"
puts "  Encoding.compatible?(plain, latin1)  #{Encoding.compatible?(plain, latin1).inspect}"
puts
puts "Comparing, which never raises:"
puts "  utf8 == latin1                         #{utf8 == latin1}"
puts "  utf8 == latin1.encode(\"UTF-8\")         #{utf8 == latin1.encode("UTF-8")}"
puts "  \"abc\" == \"abc\".encode(\"ISO-8859-1\")    #{"abc" == "abc".encode("ISO-8859-1")}"
prices = { utf8 => 3 }
puts "  { utf8 => 3 }[latin1]                  #{prices[latin1].inspect}"
