Accent stress - ASCII - How to get rid of strange characters

I just spent some hours to solve a problem that many people must have :
How to correctly show Latin accent characters in rails?

The problem is that usually, you get all ‘?’ when sending to the
browser things like ‘ç’, ‘ã’ etc.

I spent many hours dealing with this, but couldn’t find a good solution
from Mr. Google.

So, I wrote the following method :

def to_h(string)
saida=""
asci = Hash.new
for i in 1…255
asci[i.chr] = i
end
string.each_char do |charac|
saida = saida+ “&#”+asci[charac].to_s
end
return saida
end

You should put it either in the application_helper.rb and at the
controllers application.rb, so that you can call it either from a view
and from a controller.

Basically, it encodes the string in ‘&#’ codes that are standard html
for the ‘monkey’ browser.

Sweet !
Now :

<%=to_h(“atenção”) %>

outputs as :

atenção

and not as aten??o :slight_smile:

Sorry that it is not elegant enough, I had to make a ascii hash, since
I couldn’t find a standard Ruby function to do this.

If someone can help, please post.

Regards,

OK.

Hi, just knew that the [0] can return the ascii code :
e.g. : “A”[0] >> 65
So, the method is :

def to_h(string)
saida=""
string.each_char do |charac|
saida = saida+ “&#”+charac[0].to_s
end
return saida
end

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs