Access Ruby hash variables

人走茶凉 提交于 2019-12-31 10:41:40

问题


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":"nicholas@macpractice.com","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.


回答1:


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"



回答2:


The standard Hash treats strings and symbols differently, and I'd be willing to bet that's what's happening in this case.

Use request.params["model"]["password"] to get the password.

The exception to that is when working with a HashWithIndifferentAccess which is part of ActiveSupport. For hashes of that type, either strings or symbols can be used to access the same elements.




回答3:


Try the below,it will work too:

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


来源:https://stackoverflow.com/questions/16194219/access-ruby-hash-variables

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!