Project

General

Profile

Bug #9533 » hash_flatten_fix.patch

taksski (Takeshi Sasaki), 02/19/2014 03:25 PM

View differences:

hash.c
2367 2367
 *     a =  {1=> "one", 2 => [2,"two"], 3 => "three"}
2368 2368
 *     a.flatten    # => [1, "one", 2, [2, "two"], 3, "three"]
2369 2369
 *     a.flatten(2) # => [1, "one", 2, 2, "two", 3, "three"]
2370
 *     a.flatten(0) # => [[1, "one"], [2, [2, "two"]], [3, "three"]]
2371
 *     a.flatten(-1) # => [1, "one", 2, 2, "two", 3, "three"]
2370 2372
 */
2371 2373

  
2372 2374
static VALUE
2373 2375
rb_hash_flatten(int argc, VALUE *argv, VALUE hash)
2374 2376
{
2375 2377
    VALUE ary;
2378
    int level;
2376 2379

  
2377 2380
    ary = rb_ary_new_capa(RHASH_SIZE(hash) * 2);
2378 2381
    rb_hash_foreach(hash, flatten_i, ary);
2379
    if (argc) {
2380
	int level = NUM2INT(*argv) - 1;
2381
	if (level > 0) {
2382
	    *argv = INT2FIX(level);
2383
	    rb_funcall2(ary, rb_intern("flatten!"), argc, argv);
2384
	}
2385
    }
2382
    if (!argc) {
2383
      return ary;
2384
    }
2385
    
2386
    level = NUM2INT(*argv);
2387
    if (!level) {
2388
      ary = rb_hash_to_a(hash);
2389
    } else {
2390
      if (level > 0) {
2391
	level--;
2392
      }
2393
      if (!level) {
2394
	return ary;
2395
      }
2396
      *argv = INT2FIX(level);
2397
      rb_funcall2(ary, rb_intern("flatten!"), argc, argv);
2398
    }
2399
    
2386 2400
    return ary;
2387 2401
}
2388 2402

  
test/ruby/test_hash.rb
974 974

  
975 975
    a =  @cls[1=> "one", 2 => [2,"two"], 3 => [3, ["three"]]]
976 976
    assert_equal([1, "one", 2, [2, "two"], 3, [3, ["three"]]], a.flatten)
977
    assert_equal([1, "one", 2, [2, "two"], 3, [3, ["three"]]], a.flatten(-1))
978
    assert_equal([1, "one", 2, [2, "two"], 3, [3, ["three"]]], a.flatten(0))
977
    assert_equal([1, "one", 2, 2, "two", 3, 3, "three"], a.flatten(-1))
978
    assert_equal([[1, "one"], [2, [2, "two"]], [3, [3, ["three"]]]], a.flatten(0))
979 979
    assert_equal([1, "one", 2, [2, "two"], 3, [3, ["three"]]], a.flatten(1))
980 980
    assert_equal([1, "one", 2, 2, "two", 3, 3, ["three"]], a.flatten(2))
981 981
    assert_equal([1, "one", 2, 2, "two", 3, 3, "three"], a.flatten(3))