【发布时间】:2025-11-26 23:10:02
【问题描述】:
我一直在尝试使用“&”相交方法与 Ruby 中的 Twitter API 相交数组。我已经尝试了几种不同的方法,它只是说......“Twitter的未定义方法`&'......”。 “|”也是一样的和 ”-”。我读过的所有文档都说您只需要使用“&”来与数组相交并获得一个具有相同值的新数组。我对 Ruby 很陌生,我错过了什么?...
@var = @array1 & @array2
我的控制器代码如下:
class UsersController < ActionController::Base
def index
redirect_to :controller => 'users', :action => 'show', :id => params[:id]
end
def show
begin
@users = $client.user_timeline(params[:id])[0..9] #Gets last 10 tweets
@userinfo = $client.user(params[:id])
@friends = $client.friend_ids(@userinfo.id)
rescue Twitter::Error::NotFound
redirect_to :controller => 'users', :action => 'show', :id => '404'
end
end
def compare
@users = $client.user_timeline(params[:id])[0..0] #Limits Timeline request to 1
@users2 = $client.user_timeline(params[:id2])[0..0] #Limits Timeline request to 1
@userinfo = $client.user(params[:id])
@userinfo2 = $client.user(params[:id2])
@friendlists = $client.friend_ids(@userinfo.id) #Variable 1
@friendlists2 = $client.friend_ids(@userinfo2.id) #Variable 2
end
end
我的查看代码是...
<% @friendmerge = @friendlists & @friendlists2 %> #<--This should work right?
<% if !@friendmerge.blank? %>
<pre><%= JSON.pretty_generate(@friendmerge) %></pre>
<% else %>
This didn't work.
<% end %>
我是 Ruby 新手,所以请善待。我完全意识到我可能正在为一些核心原则而苦苦挣扎。感谢您提供任何和所有帮助。
【问题讨论】:
-
你能打印出朋友列表是什么样的吗?
-
如果您的错误消息显示“未定义的方法 `&' for Twitter...”,那么您有一个
Twitter对象,而不是Array。 -
泽。感谢你的回答。当我将它转换为一个对象时,它将打印为一个数组(谢谢!)......但是,当我尝试相交时,@friendmerge 变量为空白并且不打印。我知道有大约 200 个与我正在比较的用户相交的项目,所以它应该打印出来……除非我遗漏了其他东西。
-
您检查过friendlists 和friendlists2 变量数据类型吗?我猜这不是一个数组。
标签: ruby-on-rails ruby arrays ruby-on-rails-4 intersection