ipsum
ipsum

Reputation: 1052

Is there a cleaner way to write this? (Ruby/Rails blocks, return value)

  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  

Upvotes: 0

Views: 364

Answers (5)

Mike Woodhouse
Mike Woodhouse

Reputation: 52316

How about

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

?

Upvotes: 2

Jeremy Weiskotten
Jeremy Weiskotten

Reputation: 978

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

Upvotes: 2

Deepak N
Deepak N

Reputation: 2571

Another option is returning block

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

Upvotes: 3

Wayne Conrad
Wayne Conrad

Reputation: 107959

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

Upvotes: 3

Lavir the Whiolet
Lavir the Whiolet

Reputation: 1016

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 }

Upvotes: 0

Related Questions