Rails 哈希到数组到哈希如何?
在我的控制器中,我有:
def index
@title = 'asdsadas'
@kategoris = Tag.where("name like ?", "%#{params[:q]}%")
@kate = @kategoris.map(&:attributes).map{|d| d.map{|d| d.map{|d| d.dup.force_encoding("UTF-8") if d.respond_to?(:force_encoding) } } }
respond_to do |format|
format.html
format.json { render :json => @kate }
end
end
问题是它已经变成了一个数组:
[[["cached_slug","vinna-biljetter"],["created_at",null],["h1","inn biljetter - Delta i tävl
它应该是一个散列:
[{"cached_slug":"vinna-biljetter","created_at":"2011-04-28T10:33:05Z","h1":"inn biljetter -
In my controller I have:
def index
@title = 'asdsadas'
@kategoris = Tag.where("name like ?", "%#{params[:q]}%")
@kate = @kategoris.map(&:attributes).map{|d| d.map{|d| d.map{|d| d.dup.force_encoding("UTF-8") if d.respond_to?(:force_encoding) } } }
respond_to do |format|
format.html
format.json { render :json => @kate }
end
end
The problem is it has become an array:
[[["cached_slug","vinna-biljetter"],["created_at",null],["h1","inn biljetter - Delta i tävl
It should be a hash:
[{"cached_slug":"vinna-biljetter","created_at":"2011-04-28T10:33:05Z","h1":"inn biljetter -
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
试试这个:
OR
@kate
现在是一个哈希数组。Try this:
OR
@kate
is now an array of hashes.试试这个:
PS:
上面的解决方案仅选择支持
force_encoding
的值。如果您想包含其他值:Try this:
PS:
The solution above selects only the values that support
force_encoding
. If you want to include other values:总有 Hash[*] 技巧:
There's always the Hash[*] trick:
这可能还不能完全回答问题
如果您只想将哈希转换为数组,只需对哈希调用 to_a 即可。
参考:
https://ruby-doc.org/core- 2.5.0/Hash.html#method-i-to_a
This may not completely answer the question, still
If you just want to convert a Hash to Array, just call to_a on the hash.
Reference:
https://ruby-doc.org/core-2.5.0/Hash.html#method-i-to_a