[macruby-changes] [4966] MacRuby/trunk/NSArray.m

source_changes at macosforge.org source_changes at macosforge.org
Thu Dec 2 00:58:48 PST 2010


Revision: 4966
          http://trac.macosforge.org/projects/ruby/changeset/4966
Author:   watson1978 at gmail.com
Date:     2010-12-02 00:58:44 -0800 (Thu, 02 Dec 2010)
Log Message:
-----------
Array#join will return a string when Array include the object which has the to_ary/to_str/to_s.

Test Script:
{{{
require 'test/unit/assertions.rb'
include Test::Unit::Assertions

class Join
  def initialize(*arg)
    @arg = arg
  end
end

class Ary1 < Join
  def to_ary
    @arg.to_a
  end
end

class Ary2 < Join
  def to_a
    @arg.to_a
  end
end

class Str1 < Join
  def to_str
    @arg.to_s
  end
end

class Str2 < Join
  def to_s
    @arg.to_s
  end
end

class AryStr < Join
  def to_s
    @arg.to_s
  end
  def to_ary
    @arg.to_a
  end
end

a1 = Ary1.new(1, 2, 3, 'test')
ary = ['#', a1]
assert_equal("#123test", ary.join)

a2 = Ary2.new(1, 2, 3, 'test')
ary = ['#', a2]
assert_match(/##<Ary2:0x[a-f\d]+>/, ary.join) # not string

s1 = Str1.new(123)
ary = ['#', s1]
assert_equal("#[123]", ary.join)

s2 = Str2.new(456)
ary = ['#', s2]
assert_equal("#[456]", ary.join)

t = AryStr.new(789)
ary = ['#', t]
assert_equal("#789", ary.join)

puts :ok
}}}

Modified Paths:
--------------
    MacRuby/trunk/NSArray.m

Modified: MacRuby/trunk/NSArray.m
===================================================================
--- MacRuby/trunk/NSArray.m	2010-12-02 07:18:40 UTC (rev 4965)
+++ MacRuby/trunk/NSArray.m	2010-12-02 08:58:44 UTC (rev 4966)
@@ -1188,7 +1188,20 @@
 		}
 		break;
 	    default:
-		elem = rb_obj_as_string(elem);
+		{
+		    VALUE tmp = rb_check_string_type(elem);
+		    if (!NIL_P(tmp)) {
+			elem = tmp;
+			break;
+		    }
+		    tmp = rb_check_convert_type(elem, T_ARRAY, "Array", "to_ary");
+		    if (!NIL_P(tmp)) {
+			VALUE args[2] = {tmp, sep};
+			elem = rb_exec_recursive(recursive_join, elem, (VALUE)args);
+			break;
+		    }
+		    elem = rb_obj_as_string(elem);
+		}
 		break;
 	}
 	if (i > 0 && !NIL_P(sep)) {
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.macosforge.org/pipermail/macruby-changes/attachments/20101202/2ce55329/attachment-0001.html>


More information about the macruby-changes mailing list