Forum: Ruby Dynamically naming an Object

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
John G. (Guest)
on 2008-10-09 06:26
I'm new to ruby, so this may be simple, but I can not figure it out.
Simply, I am wanting to dynamically create objects at runtime with a
variable name also given at runtime.

for example -

keys = []

word = ""

while word != "end"
  word = (gets.chomp)
  word = word.downcase
  keys.push(word) unless word == "end"
end

class Word
end

keys.each { |new_obj| new_obj = Word.obj

[user input of win]

puts win.inspect

I know it may sound strange, but I am just playing.  Any help would be
greatly appreciated.

-M
John G. (Guest)
on 2008-10-09 06:30
John G. wrote:

> keys.each { |new_obj| new_obj = Word.obj
  keys.each { |new_obj| new_obj = Word.new
sorry about that, I'm a bit flustered.
Robert K. (Guest)
on 2008-10-09 11:41
(Received via mailing list)
2008/10/9 John G. <removed_email_address@domain.invalid>:
> while word != "end"
> [user input of win]
>
> puts win.inspect
>
> I know it may sound strange, but I am just playing.  Any help would be
> greatly appreciated.

You did not state which objects you want to dynamically generate names
for...

Regardless: generating local variable names does not work as you might
expect because local variables which are not known at compile time of
the script code cannot be used easily. Rather use a Hash which seems
the more appropriate data structure in your case anyway.

Kind regards

robert
This topic is locked and can not be replied to.