【问题标题】:UTF-8 string in RubyRuby 中的 UTF-8 字符串
【发布时间】:2011-04-16 13:51:10
【问题描述】:

我有以下模块:

# encoding: utf-8
module RandomNameModule

    def self.doesNothing(word)
        str = ""
        word.codepoints{|val|
            str << val.chr
        }
        return str
    end
end

以及以下测试:

# encoding: utf-8
require 'test/unit'
require '../src/RandomNameModule.rb'

class RandomNameTests < Test::Unit::TestCase
    def testDoesNothing
        sorted = WordSort.word_sort("£$&")
        assert_equal("£$&", sorted)
    end
end

当我运行测试时,我得到一个断言失败:

<"£$&"> expected but was
<"\xA3$&">.

这是因为"£".codepoints{|x| x.chr} 返回值\xA3

我怎样才能让这个返回£

【问题讨论】:

    标签: ruby utf-8 character-encoding ruby-1.9.2


    【解决方案1】:

    如果您没有明确告诉它使用什么编码,您的示例中使用的 Integer#chr 方法似乎默认为 ASCII:

    def self.doesNothing(word)
      str = ""
      word.codepoints { |val| str << val.chr("utf-8") }
      str
    end
    

    此外,使用String#each_char 代替String#codepoints 也可以正常工作:

    def self.doesNothing(word)
      str = ""
      word.each_char { |val| str << val }
      str
    end
    

    【讨论】:

    • 谢谢!我不能使用 each_char,因为我也需要 utf-8 整数值。
    猜你喜欢
    • 2023-03-23
    • 2014-01-18
    • 2011-07-29
    • 2013-04-07
    • 2013-07-07
    • 2019-01-09
    • 1970-01-01
    • 2023-03-27
    • 2013-01-16
    相关资源
    最近更新 更多