访问Ruby哈希变量 [英] Access Ruby hash variables
问题描述
put'/ user_list /:user_id' do
puts request.params [model]
end
返回以下
{password:36494092d7d5682666ac04f62d624141,username:nicholas,user_id:106, firstname:Nicholas,email:nicholas@macpractice.com,is_admin:0,lastname:Rose,privileges:}
现在我很难访问每个值的值。它似乎并不是真正的哈希格式,所以我真的不能这样做。
$ $ $ $ $ $ $ $ $ request.params [model] [:密码]
它只是返回零。
我只需要知道我可以做些什么来访问这些变量,或者如何配置我的请求参数,以便以良好格式访问变量。 >解决方案
试试 request.params [model] [password] $ b <一个 Hash
的键可以由符号和字符串组成。但是,字符串键与符号键不同。
请注意以下几点:
h = {:name => 'Charles',name=> 'Something else'}
h [:name]#=> 'Charles'
h [name]#=> 'Something else'
编辑:
在特定情况下,它显示为 request.params [model]
返回一个字符串而不是散列。有一种方法 String#[]
这是获取子串的方法。
s =冬天来了
s [Winter]#=> 冬天
s [Summer]#=>无
这会解释您的评论。
您可以采取一些措施来纠正您的具体情况。我找到了使用 JSON
最简单的方法。 (我确信还有其他人,也许这些将通过其他答案或通过评论。)
require'json'
hash_of_params = JSON.load(request.params [model])。to_hash
hash_of_params [password]#=> 36494092d7d5682666ac04f62d624141
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.
解决方案 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"
这篇关于访问Ruby哈希变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!