Twitter API实现"趋势"

时间:2014-07-25 17:53:00

标签: ruby api twitter

我正在尝试使用Twitter API列出趋势主题。在调用我的函数并分配给" X" (然后打印" X")我返回(用JSON解析)看起来像这样的东西:

puts X

{"trends"=>[{"name"=>"blah blah", "query" =>"blah blah" and a bunch more info...
            {"name"=>"blah2 blah2", "query"=>"blah blah" and a bunch more...
            {"name"=>"blah3 blah3", and so on and so forth.}]}

我可以通过调用

来接近我想要的输出
X.each do |T|
  puts T["trends"]
end

我可以这样打印每一行:

{"name"=>"blah blah", "query" =>"blah blah" and a bunch more information
{"name"=>"blah2 blah2", "query"=>"blah blah" and a bunch more...
{"name"=>"blah3 blah3", and so on and so forth.}

如何让我的代码只打印趋势主题的名称?

我认为这将是一些事情
X.each do |T|
  puts T["trends"]["name"]
end

但这不起作用。如何才能显示

blah  blah
blah2 blah2
blah3 blah3

按照地区 当我调用以下内容时,我从String转换为Integer错误。

X["trends"].each do |T|
    puts T["name"]
end

当我打电话给X.inspect时,我只是把我放在问题的顶部,并在趋势中添加了一组[]。

[{"trends"=>[{"name"=>"blah blah", "query" =>"blah blah" and a bunch more info...
            {"name"=>"blah2 blah2", "query"=>"blah blah" and a bunch more...
            {"name"=>"blah3 blah3", and so on and so forth.}]}]

我明白了。

X.each do |trend|
    trend["trends"].each do |topic|
        puts topic["name"]
    end
end

1 个答案:

答案 0 :(得分:0)

你必须迭代'trends'

response = {"trends"=>[{"name"=>"blah blah", "query" =>"blah blah" and a bunch more information
            {"name"=>"blah2 blah2", "query"=>"blah blah" and a bunch more...
            {"name"=>"blah3 blah3", and so on and so forth.}]}

response['trends'].each do |trend|
  trend['name'] # do what you want with this
end

或者获取所有名称的数组:

response['trends'].map { |t| t['name'] }
# => ["blah blah", "blah2 blah2", "blah3 blah3"]