2017-04-17 66 views
0

我通过活动记录从postgres数据库获取字符串,并且需要将其转换为UTF-8代码列表。将字符串转换为Ruby on Rails中的UTF-8代码列表

我从数据库中获取的代码是波斯语字符,所以它应该看起来像一个阿拉伯字符。

def convertHex 

    @user=DoctorProfile.where(id: params[:id]) 
    # [email protected](:first_name) 
    ar=Array.new 
    pri=Array.new 
    [email protected](:first_name) 
    ar.split(",").map { |s| s.to_s } 

    ar.each do |p| 
    pri.push(p.ord.to_s + " , ") 
    end 

    # [email protected]("") 
    # ar = ar.each_byte.map { |b| b.to\_s(16) }.join 
    #ar.each do |c| 
    # b=b +','+ c 
    #end 

    render json: pri ,status:200 
end 

我得到这个

[ 
    "1590 , " 
] 

但我想是这样的:

[ 
    "1590 , 2123 , 1112 , ..." 
] 
+0

喜桑德罗。这个答案有点混乱,但我认为可以改进。 (1)它需要适当的缩进。 (2)1590不是有效的ASCII码(ASCII值是7或8位长),所以我认为你可能在寻找UTF码,而不是ASCII码,但这个问题应该澄清一下。 (3)通过将转换放在单独的函数中,您可以将此问题重写为纯Ruby,而不使用Rails。然后可以显示如何使用该功能,显示您正在给该功能的实际输入。 –

+0

是的,我需要utf不ascii对不起 – Sandro

+0

1590是正确的这是一个波斯字符,但2123,1112是假的,我花了两天在这种情况下,我绝对不知道我该怎么处理这个案件 – Sandro

回答

2

您可以使用String#unpack()方法,decodes str (which may contain binary data) according to the format string, returning an array of each value extracted

# find will already return an object, not an array 
# note it will throw an exception if user with id doesn't exist 
# to get nil instead of exception, use find_by_id(params[:id]) 
@user = DoctorProfile.find(params[:id]) 

char_codes = @user.first_name.unpack('U*') 

或者,如果first_name可能nil,您可以用安全导航操作处理:

char_codes = @user.first_name&.unpack('U*') || [] 

U代表UTF-8,和*会占用所有剩余的元素。

它将返回码的数组:

"Any Name".unpack('U*') 
# => [65, 110, 121, 32, 78, 97, 109, 101] 

如果你需要用逗号分隔码的String(如你的例子),你可以简单地join它:

char_codes.join(', ')