How to name a variable after another variable's value?

All-

Is there a way to name a variable partly after the value of some other variable:

I tried to do something like this:

greeting_no = "2"
sp#{greeting_no}_greeting = 'Hello'

…with the idea of making 2nd line equivalent to writing:

sp2_greeting = "Hello"

…but this didn’t work.

Thanks!

-Kurt

Kurt Euler wrote:

I tried to do something like this:
greeting_no = "2"
sp#{greeting_no}_greeting = ‘Hello’

greeting_no = "2"
eval “sp#{greeting_no}_greeting = ‘Hello’”

But why not just use an Array or Hash?
sp_greeting[mykey] = ‘Hello’

kind regards,
Norbert

try something like:

greeting_no = "2"
attr “sp#{greeting_no}_greeting”.intern

and then you can do:

send(“sp#{greeting_no}_greeting=”,‘Hello’)

~transami

···

On Thu, 2002-07-18 at 00:37, Kurt Euler wrote:

All-

Is there a way to name a variable partly after the value of some other variable:

I tried to do something like this:

greeting_no = "2"
sp#{greeting_no}_greeting = ‘Hello’

…with the idea of making 2nd line equivalent to writing:

sp2_greeting = “Hello”

…but this didn’t work.

Thanks!

-Kurt


~transami

(") dobee dobee do…
\v/
^ ^

There’s always eval, but… I have to ask; why do [you think] you
need this? I ask my question only semi rhetorically, because
whenever I thought I needed something like that, I typically found
that I was thinking about the problem wrong. In other words, a
design smell that led to a code smell.

You might also consider an array, and index by “greeting_no”.

···

— Kurt Euler keuler@portal.com wrote:

All-

Is there a way to name a variable partly after the value of some
other variable:

I tried to do something like this:

greeting_no = "2"
sp#{greeting_no}_greeting = ‘Hello’

…with the idea of making 2nd line equivalent to writing:

sp2_greeting = “Hello”

…but this didn’t work.

=====

Use your computer to help find a cure for cancer: http://members.ud.com/projects/cancer/

Yahoo IM: michael_s_campbell


Do You Yahoo!?
Yahoo! Autos - Get free new car price quotes

Hello –

Kurt Euler wrote:

I tried to do something like this:
greeting_no = "2"
sp#{greeting_no}_greeting = ‘Hello’

greeting_no = "2"
eval “sp#{greeting_no}_greeting = ‘Hello’”

I agree that using a Hash is almost certainly a much better design –
but I just want to point out that in the above example, the variable
you create that way will only be visible in the eval block:

$ ruby -vwe ‘a=“b”; eval “#{a}=1; puts b”; puts b’
ruby 1.6.7 (2002-03-01) [i686-linux]
1
-e:1: undefined local variable or method `b’ for
#Object:0x401c8ce0 (NameError)

David

···

On Thu, 18 Jul 2002, Norbert Gawor wrote:


David Alan Black
home: dblack@candle.superlink.net
work: blackdav@shu.edu
Web: http://pirate.shu.edu/~blackdav