[MacRuby-devel] NSArray's count and Ruby Array#count

Laurent Sansonetti lsansonetti at apple.com
Tue Oct 5 14:15:26 PDT 2010


Hi Caio,

You found out an exception :) As you know, NSArray responds to -count which simply return the number of elements it contains. But Ruby Array defines #count which has different semantics.

To not conflict with NSArray, the Ruby #count is only defined on Ruby arrays.

However, I do not understand where #count is used in your snippet. Is it used in Pathname?

Laurent

On Oct 4, 2010, at 12:14 AM, Caio Chassot wrote:

> Hi all,
> 
> Code first:
> 
>    cocoa_array = NSArray.new
>    ruby_array  = []
> 
>    puts ruby_array.count               # => 0
>    puts ruby_array.count { true }      # => 0
>    puts ruby_array.count("whatever")   # => 0
> 
>    puts cocoa_array.count              # => 0
>    puts cocoa_array.count { true }     # => 0 # unknown: warning: passing a block to an Objective-C method - will be ignored
>    puts cocoa_array.count("whatever")  # => wrong number of arguments (1 for 0) (ArgumentError)
> 
> I originally ran into this issue in the following code, where the fact that we have an NSArray, and not a ruby array ends up concealed by the bajillion of ruby-ish method calls such as  compact and map:
> 
>    paths_from_clipboard = NSPasteboard.generalPasteboard.pasteboardItems
>      .map { |pbi | pbi.stringForType('public.file-url') }.compact
>      .map { |url | NSURL.URLWithString(url).path }
>      .map { |path| Pathname.new(path) }
> 
> 
> Full, pretty and colorful version: http://gist.github.com/602174
> 
> 
> What's going on there is that NSArrays (but not NSMutableArrays) will use the vanilla Cocoa's count method.
> 
> So I'm resorting to doing:
> 
>    Array.new(SomeCocoaClass.withAMethodThatReturnsAnNSArray)
> 
> 
> I wonder, is this a bug or "works as designed"?
> 
> 
> 
> 
> _______________________________________________
> MacRuby-devel mailing list
> MacRuby-devel at lists.macosforge.org
> http://lists.macosforge.org/mailman/listinfo.cgi/macruby-devel

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.macosforge.org/pipermail/macruby-devel/attachments/20101005/061969a5/attachment.html>


More information about the MacRuby-devel mailing list