From: Kenichi Komiya Date: 2001-07-20T11:06:12+09:00 Subject: [ruby-talk:18160] Re: Opaque constants? (in C?) Hi, From: Emil Ong Subject: [ruby-talk:18150] Opaque constants? (in C?) Date: Fri, 20 Jul 2001 07:16:35 +0900 > Is it possible to define opaque constants in ruby similar to true and > false? That is, if you were using irb and you wanted the value of the > constant 'my_const', you would get something like this: You can make an object 'opaque' by defining "inspect" as a singleton method, so that it always returns "it's name". So, if you can live with captalized constant... irb(main):001:0> MY_CONST = Object.new # irb(main):002:0> MY_CONST # irb(main):003:0> def MY_CONST.inspect; "MY_CONST".freeze; end nil irb(main):004:0> MY_CONST MY_CONST You can chose to define a uncapitalized pseudo constant (a method always return the same object). class Object obj = Object.new define_method(:my_const) { obj } end def my_const.inspect "my_const".freeze end In many situations, it works as if it is constant. But, using non-standard naming convention like this decrease readability, IMHO. > Moreover, can I do it from C? MY_CONST version in C. VALUE my_const = rb_obj_alloc(rb_cObject); rb_define_singleton_method(my_const, "to_s", my_const_to_s, 0); rb_define_global_const("MY_CONST", my_const); Best Regards, Kenichi Komiya.