当前位置:编程学习 > 网站相关 >>

Ruby on Rails 入门之:(4) 解决Ruby输出中文出现乱码的问题

有时候需要在ruby中输出中文,当时很多情况下会遇到输出中文是乱码或者根本没有办法运行文件的问题。

如下面的程序:


[ruby]
food = ["米饭","黑米","饺子","面条","面包"]; 
puts food; 
for item in food 
    puts item; 
end 

food = ["米饭","黑米","饺子","面条","面包"];
puts food;
for item in food
 puts item;
end
在运行的时候输出是这样的:

 

 

[plain]
watkins@watkins:~/temp/workspace/ruby$ ruby  compile.rb  
compile.rb:1: invalid multibyte char (US-ASCII) 
compile.rb:1: invalid multibyte char (US-ASCII) 
compile.rb:1: syntax error, unexpected $end, expecting ']' 
food = ["米饭","黑米","饺子","面条","面包"]; 
           ^ 
watkins@watkins:~/temp/workspace/ruby$  

watkins@watkins:~/temp/workspace/ruby$ ruby  compile.rb
compile.rb:1: invalid multibyte char (US-ASCII)
compile.rb:1: invalid multibyte char (US-ASCII)
compile.rb:1: syntax error, unexpected $end, expecting ']'
food = ["米饭","黑米","饺子","面条","面包"];
           ^
watkins@watkins:~/temp/workspace/ruby$

报告出现错误

 


为了解决在ruby中输出中文的问题,应该在ruby的文件最顶部添加下行代码,指定编码方式

#encoding:gbk

 

 

[ruby]
#encoding:gbk  
food = ["米饭","黑米","饺子","面条","面包"]; 
puts food; 
for item in food 
    puts item; 
end 

#encoding:gbk
food = ["米饭","黑米","饺子","面条","面包"];
puts food;
for item in food
 puts item;
end
然后就可以正确的执行了。


[plain]
watkins@watkins:~/temp/workspace/ruby$ ruby  compile.rb  
米饭 
黑米 
饺子 
面条 
面包 
米饭 
黑米 
饺子 
面条 
面包 
watkins@watkins:~/temp

补充:Web开发 , 其他 ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,