我有以下模块:
# 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
我怎么能使这个返回£
在你的例子中使用的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