[MacRuby-devel] A ruby string with ASCII-8BIT encoding is really an NSData and not an NSString

Carl Lerche me at carllerche.com
Fri May 28 10:03:57 PDT 2010


Hello,

I've been playing around with macruby a bunch and I hit a point of
confusion. I basically did "....".pack("H*") which returns a ruby
string. This string is an ASCII-8BIT encoded ruby string which is an
alias for a Binary string (aka, it has no encoding). IMO, this should
really be backed by an NSData class as opposed to an NSString class
because it doesn't make much sense. In fact, it's pretty much
impossible to get any useful information out of an ASCII-8BIT encoded
ruby string from the objective-c side of things.

To get around this, I did the following:

class String
  def to_data
    return NSData.data unless length > 0

    bytes = self.bytes.to_a
    p = Pointer.new_with_type("char *", bytes.length)

    bytes.each_with_index do |char, i|
      p[i] = char
    end

    NSData.dataWithBytes(p, length:bytes.length)
  end
end

I'm not sure what the solution to this is, but I thought I'd bring up
the issue on the mailing list.

Thanks,
-carl


More information about the MacRuby-devel mailing list