Project

General

Profile

Feature #3131 ยป kernel-hash.patch

runpaint (Run Paint Run Run), 09/02/2010 11:03 PM

View differences:

object.c
2388 2388
    return rb_Array(arg);
2389 2389
}
2390 2390

  
2391
VALUE
2392
rb_Hash(VALUE val)
2393
{
2394
    if (NIL_P(val)) return rb_hash_new();
2395
    VALUE tmp = rb_check_hash_type(val);
2396
    if (NIL_P(tmp)) {
2397
	if (TYPE(val) == T_ARRAY && RARRAY_LEN(val) == 0) 
2398
	    return rb_hash_new();
2399
	rb_raise(rb_eTypeError, "can't convert %s into Hash", rb_obj_classname(val));
2400
    }
2401
    return tmp;
2402
}
2403

  
2404
/*
2405
 *  call-seq:
2406
 *     Hash(arg)    -> hash
2407
 *
2408
 *  Converts <i>arg</i> to a <code>Hash</code> by calling
2409
 *  <i>arg</i><code>.to_hash</code>. Returns an empty <code>Hash</code> when
2410
 *  <i>arg</i> is <tt>nil</tt> or <tt>[]</tt>.
2411
 *
2412
 *     Hash([])          #=> {}
2413
 *     Hash(nil)         #=> nil
2414
 *     Hash(key: :value) #=> {:key => :value}
2415
 *     Hash([1, 2, 3])   #=> TypeError
2416
 */
2417

  
2418
static VALUE
2419
rb_f_hash(VALUE obj, VALUE arg)
2420
{
2421
    return rb_Hash(arg);
2422
}
2423

  
2391 2424
/*
2392 2425
 *  Document-class: Class
2393 2426
 *
......
2567 2600

  
2568 2601
    rb_define_global_function("String", rb_f_string, 1);
2569 2602
    rb_define_global_function("Array", rb_f_array, 1);
2603
    rb_define_global_function("Hash", rb_f_hash, 1);
2570 2604

  
2571 2605
    rb_cNilClass = rb_define_class("NilClass", rb_cObject);
2572 2606
    rb_define_method(rb_cNilClass, "to_i", nil_to_i, 0);
test/ruby/test_object.rb
189 189
    assert_raise(TypeError) { Array(o) }
190 190
  end
191 191

  
192
  def test_convert_hash
193
    assert_equal(Hash(nil), {})
194
    assert_equal(Hash([]), {})
195
    assert_equal(Hash(key: :value), {key: :value})
196
    assert_raise(TypeError) { Hash([1,2]) }
197
    assert_raise(TypeError) { Hash(Object.new) }
198
    o = Object.new
199
    def o.to_hash; {a: 1, b: 2}; end
200
    assert_equal(Hash(o), {a: 1, b: 2})
201
    def o.to_hash; 9; end
202
    assert_raise(TypeError) { Hash(o) }
203
  end
204

  
192 205
  def test_to_integer
193 206
    o = Object.new
194 207
    def o.to_i; nil; end