How to use "eval" to create method parameters?

  • Thread starter Iñaki Baz Castillo
  • Start date
I

Iñaki Baz Castillo

Hi, let's imagine a method "my_method()" whic allows any number of paramete=
rs.=20
And I need to create those parameters list in the following way:

lalalala =3D false
if lalalala
params =3D ":user, 'alice', 1456"
else
params =3D ":user, 0000"
end

After it I must invoke the method with "params" string as parameters.
I expected that the following could work but it fails:

my_object.my_method(eval(params))
=3D> SyntaxError: (eval):1: syntax error, unexpected ',', expecting $end
:user, 0000
^


So I don't understand how to use eval to achieve it. Any help please? Thank=
s a=20
lot.



=2D-=20
I=C3=B1aki Baz Castillo <[email protected]>
 
J

Jan Friedrich

Why not use a plain old Array?

lalalala = false
if lalalala
params = [:user, 'alice', 1456]
else
params = [:user, 0000]
end

my_object.my_method(*params)

Regards
Jan Friedrich
 
I

Iñaki Baz Castillo

El Martes, 1 de Diciembre de 2009, Jan Friedrich escribi=C3=B3:
Why not use a plain old Array?
=20
lalalala =3D false
if lalalala
params =3D [:user, 'alice', 1456]
else
params =3D [:user, 0000]
end
=20
my_object.my_method(*params)

Yes! I missed that!

Thanks a lot.

=2D-=20
I=C3=B1aki Baz Castillo <[email protected]>
 
J

Jesús Gabriel y Galán

El Martes, 1 de Diciembre de 2009, Jan Friedrich escribi=F3:
Why not use a plain old Array?

lalalala =3D false
if lalalala
=A0 params =3D [:user, 'alice', 1456]
else
=A0 params =3D [:user, 0000]
end

my_object.my_method(*params)

Yes! I missed that!

If you do have a string with comma-separated values, you can do this
(a little hackish, though):

irb(main):001:0> a =3D ":user, 'alice'"
=3D> ":user, 'alice'"
irb(main):011:0> def m *params
irb(main):012:1> p params
irb(main):013:1> end
=3D> nil
irb(main):014:0> args =3D eval("[#{a}]")
=3D> [:user, "alice"]
irb(main):015:0> m *args
[:user, "alice"]
=3D> nil

Jesus.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,065
Latest member
OrderGreenAcreCBD

Latest Threads

Top