2011-11-13 2 views
0

私のアプリには本当に奇妙なエラーメッセージが表示されています。私のコントローラでは私が持っている:Ruby on Rails Twitterの傾向 - TypeError =文字列を整数に変換できませんか?

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例外を:文字列を整数に変換できません」を取得します。

私は間違っていますか?

+0

がどの行にエラーが出たのですか? – topek

+0

<%= news ['name']%>

+0

@Joe Doyle:[クリーンアップ](http://meta.stackexchange.com/questions/128315/the-great-stack-overflow- tag-question-clean-of-2012)、これは[tag:trends]の正当な使用ではありませんか? –

答えて

2

results['trends']はタイムスタンプ=> [trends]のマップです。

トレンドの日付を選択して、トレンドの配列を反復処理する必要があります。

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" 
+0

答えに感謝しますが、どうすればいいですか?私はこれについて新しいです –

+0

それについて申し訳ありません、今私は完全な答えを見ることができます。ありがとうございました –

+0

@CarlosRaulAparicioHernandezあなたが何を見せたいかによってまったく異なります。答えに1つの例を追加します。私はスコープを制限していたのですが、なぜ例外が発生していたのですか? –