Using the variable to access object values ​​such as Javascripts object [var] in Ruby

advertisements

This question already has an answer here:

  • How to use a variable as object attribute in rails? 2 answers

In JavaScript I could do this:

var someObject = {
    bar: "Hello, world"
};
foo="bar";
console.log (someObject[foo]);

And the console would show me "Hello world"

How do I do this in ruby?

#This does not work:
@someObject.bar="Hello, world" #@someObject holds a class
foo="bar"
puts @someObject[foo]


This is driving me nuts!

I have googled. Alot. None of the possible variations I could think of with "Ruby accessing object attributes with variable" and "Accessing a variable of an object using dynamic value in ruby" gave any results. What do you call this?


It seems like you want Hash.

someObject = {bar: "Hello, world!"}  # symbol
foo = :bar
someObject[foo]
# => "Hello, world!"


anotherObject = {"bar" => "Hello, another world!"}  # string
foo = "bar"
anotherObject[foo]
# => "Hello, another world!"