Question

  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  
Was it helpful?

Solution

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

OTHER TIPS

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

Another option is returning block

  returning(users = Array.new) do |users|
      count.times { users += get_users_online }
  end

How about

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

?

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 }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top