Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access Ruby hash variables

Tags:

I am pretty new to ruby and sinatra but basically I have this route:

put '/user_list/:user_id' do
    puts request.params["model"]
end

and it returns the following

{"password":"36494092d7d5682666ac04f62d624141","username":"nicholas","user_id":106,"firstname":"Nicholas","email":"[email protected]","is_admin":0,"lastname":"Rose","privileges":""}

I am now having a hard time accessing values of each of those. It doesn't really seem to be in hash format so I can't really do

request.params["model"][:password]

It just returns nil..

I just need to know what I can do to access those variables, or how to configure my request parameters to be in a good format to access variables.

like image 787
Blaine Kasten Avatar asked Apr 24 '13 14:04

Blaine Kasten


People also ask

How do you access the hash in Ruby?

In Ruby, the values in a hash can be accessed using bracket notation. After the hash name, type the key in square brackets in order to access the value.

How do you traverse a hash in Ruby?

Iterating over a Hash You can use the each method to iterate over all the elements in a Hash. However unlike Array#each , when you iterate over a Hash using each , it passes two values to the block: the key and the value of each element.

How do I get the key-value in Ruby?

You can find a key that leads to a certain value with Hash#key . If you are using a Ruby earlier than 1.9, you can use Hash#index . Once you have a key (the keys) that lead to the value, you can compare them and act on them with if/unless/case expressions, custom methods that take blocks, et cetera.


1 Answers

Try request.params["model"]["password"]

A Hash's keys can consist of both symbols and strings. However, a string key is different than a symbol key.

Note the following:

h = {:name => 'Charles', "name" => 'Something else'}
h[:name] #=> 'Charles'
h["name"] #=> 'Something else'

EDIT:

In your particular situation, it appears request.params["model"] returns a string instead of a hash. There is a method String#[] which is a means of getting a substring.

s = "Winter is coming"
s["Winter"] #=> "Winter"
s["Summer"] #=> nil

This would explain your comments.

There are a couple things you can do to remedy your specific situation. I have found the most simplest way to be using JSON. (I'm sure there are others and maybe those will surface through other answers or through comments.)

require 'json'
hash_of_params = JSON.load(request.params["model"]).to_hash
hash_of_params["password"] #=> "36494092d7d5682666ac04f62d624141"
like image 151
Charles Caldwell Avatar answered Oct 17 '22 09:10

Charles Caldwell