Alle marted12 giugno 2007, Daniel Liebig ha scritto:
> Hi,
>
> as i mentioned before, i'm pretty new to ruby. So i'm trying to optimize
> my code and learn the advantages of this nice language :).
>
> What i'm trying this time is to pass a hash of parameters (passed by a
> HTML form i.e.) to an new Object and then automatically assign the
> values of this hash to the attributes of that object named like the keys
> of that hash.
>
> After a lot of research and even more trail & error i ended up with this:
>
> class Example
>
>    def initialize ( params = {} )
>        assign_params params unless params.nil?
>    end
>
>    def assign_params params
>      params.each { | key, value | eval "@#{key} = '#{value}'" }
>    end
>
> end
>
> At least, it works ;)
> Are there any suggestions for smarter or more efficient ways to
> accomplish this? Escpecially the usage of eval() to assign variable
> variables seems pretty workedaround to me.
>
> Thy for any hint :)
> D.

You can use instance_variable_set:

def assign_params params
  params.each_pair{|k, v| instance_variable_set( "@#{k}", v)}
end

I hope this helps

Stefano