2015-05-11 40 views
0

我試圖隨機獲取用戶朋友的列表,但是當我嘗試使用每個ID時,「each」方法似乎不起作用。請幫忙。ruby​​方法'each'not working?

我的代碼:

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>' 

謝謝您的時間和考慮:)

回答

3

因爲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] 
+0

我的每一個不工作....不是樣品方法@pangpang – marriedjane875

+0

因爲friends_list是創紀錄的,而不是一個數組,所以它簡化版,各有方法 – pangpang

+0

oooohh @pangpang謝謝你非常:D – marriedjane875

0

試試這個:

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) 
0

我們可以做到這一點 -

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) 
0

只是改變這一行

friends_list = client.friends(user).take(num_to_gather).sample 

這個

friends_list = client.friends(user).sample(num_to_gather)