Ruby Metaprogramming: dynamic instance variable names

The method you are looking for is instance_variable_set. So:

hash.each { |name, value| instance_variable_set(name, value) }

Or, more briefly,

hash.each &method(:instance_variable_set)

If your instance variable names are missing the “@” (as they are in the OP’s example), you’ll need to add them, so it would be more like:

hash.each { |name, value| instance_variable_set("@#{name}", value) }

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)