Meta programming basics

I'm sure I missed this somewhere in the Pickaxe, but what I am looking for
is a way to do this...

A = "Foo"

Assign a value to the variable named in A so at the end of the day it looks
like..

Foo = "Bar"

Thanks,
_Kevin

You have to beware that eval'ed local variables are only accessible by
eval. (And don't let irb fool you, it evals everything, so what works
there need not work in a program.)

a = "t"
eval("#{a} = 42")
eval("t") #=> 42

regards,

Brian

···

On 22/08/05, Kevin Olbrich <kevin.olbrich@duke.edu> wrote:

I'm sure I missed this somewhere in the Pickaxe, but what I am looking for
is a way to do this...

A = "Foo"

Assign a value to the variable named in A so at the end of the day it looks
like..

Foo = "Bar"

Thanks,
_Kevin

--
http://ruby.brian-schroeder.de/

Stringed instrument chords: http://chordlist.brian-schroeder.de/

I'm not aware of a way to do this with local variables, other than eval. (But then, I just figured out Struct, so what do I know? :p) However, with a Hash or OpenStruct, this is easy:

dynamic_items = {}
prop_name = "Foo"
dynamic_items[ prop_name ] = "Bar"
p dynamic_items #=> {"Foo"=>"Bar"}
puts dynamic_items[ "Foo" ] #=> Bar

require 'ostruct'
dynamic2 = OpenStruct.new
dynamic2.custom_name = 'bar'
dynamic2.send( prop_name + '=', 'Bar' )
puts dynamic2.Foo #=> Bar

See also SuperStruct, for a mix of both and dot notation (and more):
http://sstruct.rubyforge.org/

···

On Aug 22, 2005, at 7:15 AM, Kevin Olbrich wrote:

I'm sure I missed this somewhere in the Pickaxe, but what I am looking for
is a way to do this...

A = "Foo"

Assign a value to the variable named in A so at the end of the day it looks
like..

Foo = "Bar"

Gavin Kistner wrote:

See also SuperStruct, for a mix of both and dot notation (and more):
http://sstruct.rubyforge.org/

I haven't touched SuperStruct in a while... it definitely has some
bugs in it, so if you or anyone run across one, let me know.

Hal

You could also use a Hash.

values = Hash.new

a = "Foo"
values[a] = "Bar"

···

On 8/22/05, rubyhacker@gmail.com <rubyhacker@gmail.com> wrote:

Gavin Kistner wrote:

>
> See also SuperStruct, for a mix of both and dot notation (and more):
> http://sstruct.rubyforge.org/

I haven't touched SuperStruct in a while... it definitely has some
bugs in it, so if you or anyone run across one, let me know.

Hal

Oops, sorry Gavin.

···

On 8/22/05, Brian Takita <brian.takita@gmail.com> wrote:

You could also use a Hash.

values = Hash.new

a = "Foo"
values[a] = "Bar"

On 8/22/05, rubyhacker@gmail.com <rubyhacker@gmail.com > wrote:
>
> Gavin Kistner wrote:
>
> >
> > See also SuperStruct, for a mix of both and dot notation (and
> more):
> > http://sstruct.rubyforge.org/
>
> I haven't touched SuperStruct in a while... it definitely has some
> bugs in it, so if you or anyone run across one, let me know.
>
>
> Hal
>
>
>