From: Rob Biedenharn Date: 2010-11-11T07:57:44+09:00 Subject: Re: Short question about encoding. On Nov 10, 2010, at 5:34 PM, Ammar Ali wrote: > On Thu, Nov 11, 2010 at 12:01 AM, Gabriel Lichard > wrote: >> Hello everybody at the Ruby Forums! >> >> After getting more into Ruby I stumbled across a little problem: how >> would I go about making a string with a "square root" sign (√) >> inside >> it, so that it gets encoded in UTF-8 and so that I can later save >> it in >> a file? >> >> Also, I read that Ruby does have encoding-related issues, so, if >> that's >> the case, I can probably live without the "square root" sign. >> >> puts "√".encode("UTF-8") # converts it into a "v" >> puts "√" # -//- >> puts "√".force_encoding("UTF-8") # -//- >> >> Any ideas, please? > > One possibility is using the hex codes for that code point, like: > > "\xE2\x88\x9A" > > There is also a unicode escape, \u. For more information, take a > look at: > > http://ruby.runpaint.org/strings#escapes-summary > > HTH, > Ammar It seems to be fine with Ruby 1.9.2-p0. irb> sqrt = "√" => "√" irb> sqrt.encoding => # irb> sqrt.bytes => # irb> sqrt.bytes.to_a => [226, 136, 154] irb> sqrt.chars.to_a => ["√"] irb> puts sqrt √ => nil irb> puts sqrt.encode("US-ASCII") Encoding::UndefinedConversionError: U+221A from UTF-8 to US-ASCII from (irb):10:in `encode' from (irb):10 from /Users/rab/.rvm/rubies/ruby-1.9.2-p0/bin/irb:17:in `
' irb> puts sqrt.force_encoding("US-ASCII") √ => nil irb> sqrt.force_encoding("US-ASCII").chars.to_a => ["\xE2", "\x88", "\x9A"] Are you perhaps sending the output to a device that does not understand UTF-8? -Rob Rob Biedenharn Rob@AgileConsultingLLC.com http://AgileConsultingLLC.com/ rab@GaslightSoftware.com http://GaslightSoftware.com/