Creating and naming variables dynamic

Hi all,

I want to create a variable dynamic. I have defined some classes and
depending on data I get from a database I need to construct an object
eg:

now I do

if type==“car”
variab = Car.new
elsif type=“boat”
variab = Boat.new
end

can I do something like
variab = Instance.new(type)

Following this: can I give dynamic variablenames?
now I do
if type==“car”
car_string = Car.new
elsif type=“boat”
boat_string = Boat.new
end

can I do something like
dynamicpart_string = Instance.new(type)

Regards,
Stijn

Hi –

On Tue, 29 Apr 2008, Tarscher wrote:

elsif type=“boat”
car_string = Car.new
elsif type=“boat”
boat_string = Boat.new
end

can I do something like
dynamicpart_string = Instance.new(type)

Fred Cheung has answered this post for you on the Rails mailing list.

David

if type can be either ‘car’ or ‘boat’ i.e. lowercase strings:

my_class = Object.const_get(type.capitalize)

and then

my_class.new

etc.

alternatively, you can look into active_support, where you have stuff
like

“string”.classify.constantize.new(“aa”)
=> “aa”

HTH,
Peter


http://www.rubyrailways.com
http://scrubyt.org

On 28.04.2008 17:03, Tarscher wrote:

elsif type=“boat”
variab = Boat.new
end

can I do something like
variab = Instance.new(type)

More options

factory = {
“car” => Car,
“boat” => Boat,
}

var = factory[type].new

Following this: can I give dynamic variablenames?
now I do
if type==“car”
car_string = Car.new
elsif type=“boat”
boat_string = Boat.new
end

can I do something like
dynamicpart_string = Instance.new(type)

Better use a Hash for this

vars = {}
vars[type] = factory[type].new

Cheers

robert

You can try methods instead of dynamic variables, but the best option is
the
one above with hash.

self.class.send(:define_method,
type){Object.const_get(type.capitalize);}

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs