From 16b174dd46e4698103de916e69e465984cb05a67 Mon Sep 17 00:00:00 2001 From: Mark Dodwell Date: Wed, 4 Jul 2012 02:14:00 -0700 Subject: [PATCH] Add Kernel#Symbol conversion method like String(), Array() etc. --- include/ruby/intern.h | 1 + object.c | 24 ++++++++++++++++++++++++ test/ruby/test_object.rb | 10 ++++++++++ 3 files changed, 35 insertions(+) diff --git a/include/ruby/intern.h b/include/ruby/intern.h index e5167c6..327c0d1 100644 --- a/include/ruby/intern.h +++ b/include/ruby/intern.h @@ -557,6 +557,7 @@ VALUE rb_Float(VALUE); VALUE rb_String(VALUE); VALUE rb_Array(VALUE); VALUE rb_Hash(VALUE); +VALUE rb_Symbol(VALUE); double rb_cstr_to_dbl(const char*, int); double rb_str_to_dbl(VALUE, int); /* parse.y */ diff --git a/object.c b/object.c index f890d49..695fdbe 100644 --- a/object.c +++ b/object.c @@ -2662,6 +2662,29 @@ rb_f_hash(VALUE obj, VALUE arg) } /* + * call-seq: + * Symbol(arg) -> Symbol + * + * Converts arg to a Symbol by calling its + * to_sym method. + * + * Symbol("string") #=> :string + * Symbol(123456) #=> :"123456" + */ + +static VALUE +rb_f_symbol(VALUE obj, VALUE arg) +{ + return rb_Symbol(arg); +} + +VALUE +rb_Symbol(VALUE val) +{ + return rb_convert_type(val, T_SYMBOL, "Symbol", "to_sym"); +} + +/* * Document-class: Class * * Classes in Ruby are first-class objects---each is an instance of @@ -2920,6 +2943,7 @@ Init_Object(void) rb_define_global_function("String", rb_f_string, 1); rb_define_global_function("Array", rb_f_array, 1); rb_define_global_function("Hash", rb_f_hash, 1); + rb_define_global_function("Symbol", rb_f_symbol, 1); rb_cNilClass = rb_define_class("NilClass", rb_cObject); rb_define_method(rb_cNilClass, "to_i", nil_to_i, 0); diff --git a/test/ruby/test_object.rb b/test/ruby/test_object.rb index 70dcd04..6c65236 100644 --- a/test/ruby/test_object.rb +++ b/test/ruby/test_object.rb @@ -210,6 +210,16 @@ class TestObject < Test::Unit::TestCase assert_raise(TypeError) { Hash(o) } end + def test_convert_symbol + o = Object.new + def o.to_sym; "foo"; end + assert_raise(TypeError) { Symbol(o) } + def o.to_sym; :foo; end + assert_equal(:foo, Symbol(o)) + def o.respond_to?(*) false; end + assert_raise(TypeError) { Symbol(o) } + end + def test_to_integer o = Object.new def o.to_i; nil; end -- 1.7.11.1