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

Josh Ballanco joshua.ballanco at apple.com
Fri May 28 11:07:17 PDT 2010


On May 28, 2010, at 10:03 AM, Carl Lerche wrote:

> Hello,

Hi!

> 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.

All true statements. The problem, however, is with Ruby. Ruby's use of Strings to hold random binary data goes back a long way, and is deeply ingrained in a lot of Ruby libraries. It has even led to some ugly habits, like using regular expressions to parse binary data. 

Unfortunately, this also means that it would be very difficult to replace a Ruby binary string with an NSData without also re-implementing all the string methods that various Ruby libraries use. My recommendation (something I've been contemplating myself) would be to petition the ruby-core list for addition of an explicit binary data class in Ruby 2.0. In the mean time...

> 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 actually really like this! I think there's a case to be made for a set of MacRuby convenience functions for working between Ruby and Obj-C. For example, RubyCocoa's #to_plist and OSX::load_plist still need to be implemented. I'd propose a 'convenience.rb' library for all of these... Laurent?

- Josh


More information about the MacRuby-devel mailing list