0

I have the following module:

# encoding: utf-8
module RandomNameModule

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

and the following test:

# 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

When I run the test I get an assertion failure:

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

This is because "£".codepoints{|x| x.chr} returns the value \xA3

how can I make this return £

1 Answer 1

4

The Integer#chr method used in your example seems to default to ASCII if you don't explicitely tell it what encoding to use:

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

Also, using String#each_char instead of String#codepoints works fine as well:

def self.doesNothing(word)
  str = ""
  word.each_char { |val| str << val }
  str
end
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! I cant use each_char as I need the utf-8 integer value too.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.