如何从哈希中获取数据? [英] How do I get data from a hash?

查看:29
本文介绍了如何从哈希中获取数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑到这个哈希值 :params

Given this hash that comes though :params

"positions"=>{
    "1"=>{"x"=>"50", "y"=>"30"}, 
    "2"=>{"x"=>"22", "y"=>"53"}, 
    "3"=>{"x"=>"68", "y"=>"35"}
 }

我该怎么做?(不起作用,但试图展示我想做什么)

How would I do this? (doesn't work, but attempting to show what I want to do)

params[:positions].each do |position|
  logger.info(position.x)
end

我知道,初学者的东西很痛苦......

I know, painfully beginner stuff ...

我得到一个 NoMethodError(未定义方法 'x' for ["1", {"x"=>"50", "y"=>"30"}]:Array)

推荐答案

我想你想要的是

params[:positions].each do |index, coords|
  logger.info(coords['x'])
end

如果你不关心索引,你也可以使用 params[:positions].values.each do |coords| 代替.

If you don't care about the indexes, you could also just use params[:positions].values.each do |coords| instead.

这篇关于如何从哈希中获取数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆