Search code examples
rubyruby-2.3

Call property programmatically in Ruby


I have a Ruby project where I programmatically get the names of keys in a hash I need to access. I can access the fields I need in the following way:

current_content = entry.fields[property_name.to_sym]

However, it seems that some content can only be accessed with a property syntax:

m.title_with_locales = {'en-US' => 'US Title', 'nl' => 'NL Title'}

Since I don't know "title" ahead of time, how can I make a call programmatically? Ex:

m.${property_name}_with_locales = {'en-US' => 'US Title', 'nl' => 'NL Title'}

Solution

  • You can use #send to programmatically access properties:

    m.send("#{property_name}_with_locales")
    # => { 'en-US' => 'US Title', ... }
    

    If you need to access a setter and pass in values, you can do:

    m.send("#{property_name}_with_locales=", { 'whatever' => 'value' })