eclectic923
eclectic923

Reputation: 2204

does ruby need a string to class method?

I have a set of classes with static methods. Example member of class set:

    class George

    def self.ugh()
            printf( "Hello world\n" )
    end # self.ugh()

    end # class george

I need to do the following, but I don't have what I need.

    p George.object_id

The code I'm working with passes the class name (aka var). I've found a solution that seems ugly, but it works.

    var = "George" # What I have
    cmd  = "#{var}.object_id"
    p eval( cmd ) # right object_id

I would think there's a better way. Seems like ruby's missing a s_to_class() method.

The only other ideas I've found, that don't work.

    klass = class << var; self; end
    p klass.object_id # wrong object_id

    klass = var.singleton_class()
    p klass.object_id # wrong object_id

Anyone know a better way to get a class object (aka receiver) from a string/symbol?

Upvotes: 2

Views: 233

Answers (4)

Sony Santos
Sony Santos

Reputation: 5545

class A; end

id1 = A.object_id
id2 = Object.const_get("A").object_id

puts id1 == id2   #=> true

Upvotes: 0

user229044
user229044

Reputation: 239462

You could change your eval usage to make it slightly less evil:

className = "George"
klass = eval(className)
klass.objectId

But more importantly, why are you passing around class names instead of passing around the classes themselves? Class "definitions" are just objects in Ruby, and you can pass them around the same way you can pass around any other kind of object.

Upvotes: 1

Fantius
Fantius

Reputation: 3862

It seems that eval is the string to class method that you seek:

eval("George").object_id

Upvotes: 0

Skilldrick
Skilldrick

Reputation: 70869

ActiveSupport provides a constantize method, if you've got that available. Otherwise, use Module#const_get. See this question for more details.

Upvotes: 4

Related Questions