From: Iñaki Baz Castillo on
Hi, let's imagine a method "my_method()" whic allows any number of parameters.
And I need to create those parameters list in the following way:

lalalala = false
if lalalala
params = ":user, 'alice', 1456"
else
params = ":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))
=> 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? Thanks a
lot.



--
Iñaki Baz Castillo <ibc(a)aliax.net>

From: Jan Friedrich on
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
From: Iñaki Baz Castillo on
El Martes, 1 de Diciembre de 2009, Jan Friedrich escribió:
> 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)

Yes! I missed that!

Thanks a lot.

--
Iñaki Baz Castillo <ibc(a)aliax.net>

From: Jesús Gabriel y Galán on
On Tue, Dec 1, 2009 at 1:31 PM, Iñaki Baz Castillo <ibc(a)aliax.net> wrote:
> El Martes, 1 de Diciembre de 2009, Jan Friedrich escribió:
>> 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)
>
> 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 = ":user, 'alice'"
=> ":user, 'alice'"
irb(main):011:0> def m *params
irb(main):012:1> p params
irb(main):013:1> end
=> nil
irb(main):014:0> args = eval("[#{a}]")
=> [:user, "alice"]
irb(main):015:0> m *args
[:user, "alice"]
=> nil

Jesus.

 | 
Pages: 1
Prev: Pell's equation solver in Ruby
Next: Step 1.0