Search code examples
ruby

Ruby turn values inside a hash into local variables


Say I have this hash:

entry = {"director"=>"Chris Nolan", "producer"=>"Sum Duk", "writer"=>"Saad Bakk"}

I want to extract each key into its own local variable with the associated value:

director = "Chris Nolan"
producer = "Sum Duk"
...

By using a loop and not:

director = entry["director"]

Since there are a lot of values and I don't want to do them individually.

I found this which works almost perfectly except it creates an instance variable and I want a local variable, but local_variable_set doesn't exist for some reason.

entry.each_pair { |k, v| instance_variable_set("@#{k}", v) }

Is there a solution? Or failing that, a way to turn an instance variable into a local one and delete the instance one without doing it one by one?


Solution

  • You can't create local variables, because of variable scope.
    If you create a local variable inside a block, the variable would be only accessible inside the block itself.
    Please refer to this question for more info.
    Dynamically set local variables in Ruby