0
  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  

上記のコードでは、関数の最後に「users」変数を再度配置して、正しい値 (users) を返す必要があります。しかし、時間ブロックがユーザーの値を返し、関数の最後で「ユーザー」を削除できる可能性はありますか?

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

5 に答える 5

3

別のオプションはブロックを返すことです

  returning(users = Array.new) do |users|
      count.times { users += get_users_online }
  end
于 2010-10-24T17:07:19.253 に答える
3

get_users_online が呼び出されたときに同じ値を返す場合、Lavir のソリューションは適切です。そうでない場合は、次のようなものが必要です。

count.times.map {get_users_online}.flatten
于 2010-10-24T16:18:22.587 に答える
2

どうですか

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

?

于 2010-10-24T16:15:28.500 に答える
2

#タップ をご覧ください。これは、「戻る」ための新しい方法です。

def find_users_online(count = 1)   
  [].tap do |users|
    count.times { users += get_users_online }
  end
end
于 2010-10-24T17:19:24.673 に答える
0
get_users_online * count

ただし、get_users_online() は、この関数の実行中に同じ値を返す必要があります。

これがあなたのケースでない場合は、使用してください

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

またはファセットを使用する:

count.of { get_users_online }.sum

さらに興味深い方法もあります。

(1..count).inject(Array.new) { |ignore, users| users + get_users_online }
于 2010-10-24T16:03:24.100 に答える