環境 : ruby 1.8.7 + rails 2.1.0 + ubuntu 8.10
ruby 在截取 中文字符串時 經常出現亂碼 。例如:
a = "測a試 中文aaa"
b = 'test'
p a.size # 17 (可以看出一個中文字符在ruby中是3個英文字符)
p b.length # 4
puts a.slice(0,13) # 測a試 中? slice method (0是start下標處,13是length)
最后一個輸出最后 是亂碼,在java中是unicode編碼就沒有這個問題,所以我們需要轉換下編碼來解決。。
例如在rails的 application_helper.rb 定義一個轉換的方法
def cut_string(charset,src,start,length)
require "iconv"
@conv=Iconv.new("UTF-16",charset)
@reverse_conv=Iconv.new(charset,"UTF-16")
p_start=start.class==Fixnum&&start>=0
p_length=length.class==Fixnum&&length>=0
return "" unless src&&p_start&&p_length
src_utf16=@conv.iconv(src)
cutted_src_utf_16=src_utf16[2*start+2,2*length]
@reverse_conv.iconv(cutted_src_utf_16)
end
view中使用:
<%
a = '測a 試中文'
puts cut_string('UTF-8',a,0,4) # 測a 試
%>
ref:
http://my.opera.com/sawpad/blog/show.dml/235183
http://www.javaeye.com/topic/201531
補充:
真傷心,之前截取字符串,用上面的方法,還需要自己封裝,自己轉碼解決,沒想到rails已經把我們封裝好了。。就是 truncate 方法。。看了下源碼真簡單,只需要輸出對應字符串的chars 就解決了,源碼:
def truncate(text, length = 30, truncate_string = "...")
if text
l = length - truncate_string.chars.length
chars = text.chars
(chars.length > length ? chars[0...l] + truncate_string : text).to_s
end
end
使用demo:
<%
a = 'test'
b = '測試中文'
p truncate(a,2,'...') # "tes..."
p truncate(b,2,'...') # "測試中..."
%>
如果需要得到漢字的長度 可以使用 jcode 庫 里的 jlength
demo:
s = "測試140字測試140字測試140字測試140字測試140字測試140字測試140字測試140字測試140字測試140字測試140字測試140字測試140字測試
140字測試140字測試140字測試140字測試140字測試140字測試140字測試140字測試140字測試1"
$KCODE='utf8'
require 'jcode'
p s.jsize
p s.jlength
ref:
http://blog.guoshuang.com/?p=4769
http://lifegoo.pluskid.org/?p=257
posted on 2009-08-24 14:23
fl1429 閱讀(3672)
評論(0) 編輯 收藏 所屬分類:
Rails