osowskit osowskit - 1 year ago 101
Ruby Question

How to add dynamic variable into a Ruby hash at runtime

I would like to insert the value of a string into a Ruby hash at runtime. While I can do this by putting it inside a function,

def run_code(dynamic_variable)
trigger_template = {
:trigger => "#{dynamic_variable}"
.. #do something

for readability, I would like to be able to store the template outside function - or read it from a file. I tried using a template via ERB but had the result as a string - not hash. I would like to avoid making
a global variable, so storing
as a constant will complain about a missing variable.

Is there a way to delay the declaration to runtime? What is the best way to create a Hash at runtime. (The Hash is going to eventually be converted to JSON)

Answer Source

I'll just give you an example of how to load a hash from a file then modify it at runtime. You can either use JSON or YAML to serialize the Hash. For example, this is a YAML file:


foo: "bar"
bar: "foo"

Then I say

require 'yaml'
hash = YAML.load("./my/file.yaml")
hash["bar"] = "my new bar val"

put hash
# => { "foo" => "bar", "bar" => "my new bar val" }
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download