I'm still pretty new to Ruby, and am really enjoying the language. I came across this method in my code base and realized that it could be cleaned up:
def friend_all_followers(friends) client.followers.each do |follower| if not friends.include?(follower.screen_name) friend = Friend.new(:screen_name => follower.screen_name) client.friendship_create(friend.screen_name, true) friend.save end end end
So I took the above and changed it to this:
def friend_all_followers(friends) followers = client.followers.reject { |f| friends.include?(f) } followers.each do |follower| friend = Friend.new(:screen_name => follower.screen_name) client.friendship_create(friend.screen_name, true) friend.save end end
One less level of nesting, and cleaner than the first method. But I look at this method and can't help but think there's still more to be done. Any ideas?
As some background Friend
is an ActiveRecord
class, client
is a wrapper around a Twitter API, client.followers
returns an array of follower
objects - the objects I believe are just hashes, but I'm not 100% certain at the moment - and friends
is a string array of screen_name
s.