ruby方法'每个'不起作用?

时间:2015-05-11 05:43:50

标签: ruby-on-rails ruby twitter methods each

我正在尝试随机获取用户朋友的列表,但是当我尝试使用每个id时,“each”方法似乎不起作用。请帮忙。

我的代码:

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

感谢您的时间和考虑:)

4 个答案:

答案 0 :(得分: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]

答案 1 :(得分: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)

答案 2 :(得分: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)

答案 3 :(得分:0)

只需更改此行

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

到这个

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