Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby symbol to class

Is there a way in Ruby to take a symbol or string and turn it into a class of the same name?

For instance, if I have a class such as

class Bob   def talk      puts "Hi, I'm bob"   end end 

And a method I have somewhere else in the code is passed a symbol :bob, can I in some way turn that into the class Bob? Maybe something like

b = :Bob.new b.talk 

Or is there a way to do something similar to this?

like image 822
intargc Avatar asked Aug 05 '09 20:08

intargc


People also ask

What are Ruby symbols?

Ruby symbols are defined as “scalar value objects used as identifiers, mapping immutable strings to fixed internal values.” Essentially what this means is that symbols are immutable strings. In programming, an immutable object is something that cannot be changed.

How do I create a symbol in Ruby?

Ruby symbols are created by placing a colon (:) before a word. You can think of it as an immutable string. A symbol is an instance of Symbol class, and for any given name of symbol there is only one Symbol object.

What is :: in Ruby?

The :: is a unary operator and is used to access (anywhere outside the class or module) constants, instance methods and class methods defined within a class or module. Note: In Ruby, classes and methods may be considered constants too.

What does .class mean in Ruby?

What is a class in Ruby? Classes are the basic building blocks in Object-Oriented Programming (OOP) & they help you define a blueprint for creating objects. Objects are the products of the class.


1 Answers

There are many ways to do this. Your lack of context makes it impossible to elect a "best" way. Here's a few ayways.

Kernel.const_get(:Bob)  eval(:Bob.to_s)  Kernel.const_get(:bob.to_s.capitalize) 
like image 164
August Lilleaas Avatar answered Oct 05 '22 13:10

August Lilleaas