Put a string variable as a hash in another string variable

0

I have a string variable

nombre = ‘juan’

And I want to put it as hash in another variable

Todos = ( { "nombre" => ‘juan’ })

"The line above is what I want to know how to do it"

And every time the variable name changes, for example

nombre = ‘pedro’

I want to add this data as a hash in that other variable And make it look like a hash

Todos = ( { "nombre" => ‘juan’,  "nombre" => ‘pedro’ })

"The line above is what I want to know how to do it"

Thank you in advance for your prompt response.

    
asked by rrg1459 16.09.2017 в 15:02
source

1 answer

1

To create a hash (in your first example) just remove the parentheses and put the name juan in quotation marks (to indicate that it is a string ); for example:

todos = { "nombre" => "juan" }

Alternatively (and more commonly in Ruby ) you could use a symbol instead of a string as a hash key:

todos = { nombre: "juan" }

In your second case, what you need is a array where each element is a hash ; for example:

todos = [{ nombre: "juan" }, { nombre: "pedro" }]

In this example you must use an array because a hash can not have duplicate keys (e.g. nombre ).

To add another name to the list, you would simply do the following:

todos << { nombre: "carlos" }
    
answered by 16.09.2017 / 16:10
source