如何从哈希中的 get 请求访问值 (ruby)
假设我有一个获取请求:
def get (var)
uri = URI('url')
res = Net::HTTP.get_response(uri)
parse = JSON.parse(res[:body])
{parse['color'] => parse ['id']}
获取请求接受一个变量并返回一个哈希值。我知道在我的小文件中做类似的事情
get(var)['red']
会给我对应的值“红色”键。但是,如果我想通过名称访问哈希的键/值该怎么办?那么像
get(var)['color']
这样的事情可能吗? 假设请求的响应是 {'red' =>; 3} 我可以像上面的代码一样通过调用“color”来访问键“red”吗?我意识到上面代码的语法很可能是不正确的。
Say I have a get request :
def get (var)
uri = URI('url')
res = Net::HTTP.get_response(uri)
parse = JSON.parse(res[:body])
{parse['color'] => parse ['id']}
The get requests takes a variables and returns a hash. I know in my slim file doing something like
get(var)['red']
would give me the corresponding value to the key 'red'. However what if I wanted to access the key/values of the hash by their names. So something like
get(var)['color']
Would something like that be possible?
Say the response of the request was {'red' => 3}
Can I access the key 'red' by calling 'color' like in the above code. I realise the syntax of the above code is most likely incorrect.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
get 的返回值只是一个单元素哈希,如 {'red' => 3}
如果您想在不访问条目的情况下获取键和值,请使用
get(var)['red']
=>; 3
您可以执行以下操作:
get(var).keys.first
=> 'red'
get(var).values.first
=>; 3
或者您可以获取返回值并将其映射到新的哈希中:
new_hash = {"color" =>; get(var).keys.first, "id" =>get(var).values.first}
然后像这样访问:
new_hash["color"]
=>;红色
new_hash["id"]
=> 3
The returned value of get is only a single element hash like {'red' => 3}
If you want to get the key and the value without accessing the entry using
get(var)['red']
=> 3
you could do the following:
get(var).keys.first
=> 'red'
get(var).values.first
=> 3
or you could take the return value and map it into a new hash:
new_hash = {"color" => get(var).keys.first, "id" =>get(var).values.first}
then access like this:
new_hash["color"]
=> red
new_hash["id"]
=> 3