2009-10-30 16 views
6

Come posso fare questo su Ruby?Come convertire con caratteri accentati Ruby in entità speciali HTML

puts some_method("ò") 
# => "ò" 

In altre parole convertire un carattere accentato come ò alla sua versione HTML: ò

ho provato in questo modo:

# coding: utf-8 
require 'rubygems' 
require 'htmlentities' 
require 'unicode' 

coder = HTMLEntities.new 
string = "Scròfina" 
puts coder.encode(string, :named) 

ma quello che ottengo questo (da: http://htmlentities.rubyforge.org/):

/Library/Ruby/Gems/1.8/gems/htmlentities-4.2.0/lib/htmlentities/encoder.rb:85:in `unpack': malformed UTF-8 character (expected 2 bytes, given 1 bytes) (ArgumentError) 
from /Library/Ruby/Gems/1.8/gems/htmlentities-4.2.0/lib/htmlentities/encoder.rb:85:in `encode_decimal' 
from (eval):2:in `encode_extended' 
from /Library/Ruby/Gems/1.8/gems/htmlentities-4.2.0/lib/htmlentities/encoder.rb:18:in `encode' 
from /Library/Ruby/Gems/1.8/gems/htmlentities-4.2.0/lib/htmlentities/encoder.rb:18:in `gsub!' 
from /Library/Ruby/Gems/1.8/gems/htmlentities-4.2.0/lib/htmlentities/encoder.rb:18:in `encode' 
from /Library/Ruby/Gems/1.8/gems/htmlentities-4.2.0/lib/htmlentities.rb:74:in `encode' 
from unicode_pleasure.rb:8 

Grazie per il vostro tempo!

  • Leonardo
+0

Appena testato l'esempio con htmlentities 4.0.0 e tutto funziona correttamente. Non molto aiuto, lo so. :( –

risposta

12

avevo esplicitamente impostare il $ KCODE per rendere il vostro lavoro esempio. Inoltre, assicurati che il tuo file sorgente sia effettivamente codificato come UTF-8!

# coding: utf-8 
require 'rubygems' 
require 'htmlentities' 
require 'unicode' 
$KCODE = 'UTF-8' 
coder = HTMLEntities.new 
string = "Scròfina" 
puts coder.encode(string, :named) 
+0

Funziona! Grazie Jonathan! (Non posso votare perché ho meno di 15 reputazione :-( –

+0

Puoi "accettare" la risposta, però. Il parametro con nome –

+0

è stato quello che ha fatto la differenza per me . Grazie. –

Problemi correlati