views:

100

answers:

5
  def find_users_online(count = 1)        
    users = Array.new
    count.times do 
      users += get_users_online
    end
    users # <==== I want to remove this here
  end  

In the code above im must put the "users" variable again at the end of the function to return the right value (users). But is it possible that the times block return the users values and I can remove "users" at the end of the function?

  def find_users_online(count = 1)        
    users = Array.new
    count.times.and_return do # <== something like this
      users += get_users_online
    end
  end  
A: 
get_users_online * count

But get_users_online() must return the same value while executing this function.

If this is not your case then use

(1..count).map { get_users_online }.reduce(:+)

or using Facets:

count.of { get_users_online }.sum

There is also more interesting way:

(1..count).inject(Array.new) { |ignore, users| users + get_users_online }
Lavir the Whiolet
+2  A: 

How about

def find_users_online(count = 1)
  (1..count).map{ get_users_online }.flatten
end

?

Mike Woodhouse
You will get array of arrays.
Lavir the Whiolet
@Lavir: depends on what get_users_online returns, no? Adding `.flatten` would, I imagine, fix it if so.
Mike Woodhouse
In the question there were "+=" but not "<<". That implies that "get_users_online()" returns array.
Lavir the Whiolet
@Lavir. Ah. Indeed it does. Point taken.
Mike Woodhouse
+3  A: 

Lavir's solution is good if get_users_online will return the same value very time it is called. If not, you need something like this:

count.times.map {get_users_online}.flatten
Wayne Conrad
You will get array of arrays too.
Lavir the Whiolet
with this solution is must write count.times.map { get_users_online }[0] because i'm getting an array in an array
ipsum
That will result in following: [["User1", "User2"], ["User3", "User4"]] => ["User1", "User2"]
Lavir the Whiolet
Oops, I forgot that get_users_online is returning an array. Thanks, and fixed.
Wayne Conrad
+3  A: 

Another option is returning block

  returning(users = Array.new) do |users|
      count.times { users += get_users_online }
  end
Deepak N
Note that returning was removed (not even deprecated) in Rails 3 in favor of #tap.
Jeremy Weiskotten
thanks for correcting me
Deepak N
+2  A: 

Check out #tap. It's the new-fangled way to do "returning".

def find_users_online(count = 1)   
  [].tap do |users|
    count.times { users += get_users_online }
  end
end
Jeremy Weiskotten
thanks, thats exactly that i'm looking for.But I must change the += to << that it works in my case
ipsum