[英]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.