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
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
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
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 }
精彩评论