[英]ruby method 'each' not working?
我试图随机获取用户朋友的列表,但是当我尝试使用每个id时,“每种”方法似乎不起作用。 请帮忙。
我的代码:
def get_friendsids_from (user, num_to_gather)
userid_file = File.new("friends_ids.txt","a")
friends_list = client.friends(user).take(num_to_gather).sample
friends_list.each {|idnumber|
puts idnumber.followers_count
#puts client.user(idnumber).id
puts idnumber.screen_name
userid_file.puts "#{idnumber.id}"
}
end
get_friendsids_from("user", 5)
我得到的错误是:
twitter.rb:94:in `get_friendsids_from': undefined method `each' for #<Twitter::User id=2343746551> (NoMethodError)
from twitter.rb:103:in `<main>'
感谢您的时间和考虑 :)
因为friends_list
是记录,而不是数组,所以它没有each
方法。
sample: Choose a random element from the array
a = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]
a.sample #=> 7 # You just get one element ,not an array.
a.sample(4) #=> [6, 4, 2, 5]
尝试这个:
def get_friendsids_from (user, num_to_gather)
userid_file = File.new("friends_ids.txt","a")
friends_list = client.friends(user).take(num_to_gather)
friends_list.each {|idnumber|
puts idnumber.followers_count
#puts client.user(idnumber).id
puts idnumber.screen_name
userid_file.puts "#{idnumber.id}"
}
end
get_friendsids_from("user", 5)
我们做得到 -
def get_friendsids_from (user, num_to_gather)
userid_file = File.new("friends_ids.txt","a")
friends_list = client.friends(user).take(num_to_gather).sample(10)
friends_list.each {|idnumber|
puts idnumber.followers_count
#puts client.user(idnumber).id
puts idnumber.screen_name
userid_file.puts "#{idnumber.id}"
}
end
get_friendsids_from("user", 5)
只需更改此行
friends_list = client.friends(user).take(num_to_gather).sample
对此
friends_list = client.friends(user).sample(num_to_gather)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.