我的应用中收到了一条非常奇怪的错误消息。在我的控制器中,我有:
require 'open-uri'
require 'json'
class NoticiasController < ApplicationController
def index
url = 'https://api.twitter.com/1/trends/daily.json'
buffer = open(url, "UserAgent" => "Ruby-Wget").read
# convert JSON data into a hash
@result = JSON.parse(buffer)
end
end
并且在视图中我有
<div>
<% for news in @result['trends'] %>
<p><%= news['name'] %></p>
<% end %>
</div>
但我得到“TypeError:无法将String转换为Integer”。
我做错了什么?
答案 0 :(得分:2)
results['trends']
是时间戳=&gt;的地图[趋势]。
您需要选择一个趋势日期,然后迭代一系列趋势。
ruby-1.9.2-p290 :011 > result['trends'].keys.each { |k| puts k }
2011-11-13 17:00
2011-11-13 19:00
2011-11-13 14:00
2011-11-13 16:00
2011-11-13 18:00
2011-11-13 15:00
# etc.
ruby-1.9.2-p290 :022 > result['trends']["2011-11-13 17:00"].each { |t| p t["name"] }; nil
"#myweddingsong"
"#mydivorcesong"
"#ThingsPeopleShouldntDo"
"GOOD LUCK 1D"
# etc.
例如,要获取最新趋势的名称:
> ts = result['trends'].keys.sort.last
"2011-11-13 23:00"
> latest_trend_names = result['trends'][ts].collect { |t| t['name'] }
> latest_trend_names.each { |tn| p tn }
"#myweddingsong"
"#mydivorcesong"
"#ThingsPeopleShouldntDo"
"I'm a Celeb"
"HEADLESS GAGA"
"CHRIS BROWN IS A LEGEND"