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


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"
console.log (someObject[foo]);

And the console would show me "Hello world"

How do I do this in ruby?

#This does not work:"Hello, world" #@someObject holds a class
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
# => "Hello, world!"

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