これを書くよりクリーンな方法はありますか? (Ruby/Railsブロック、返品値)

StackOverflow https://stackoverflow.com/questions/4008980

質問

  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  

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

  def find_users_online(count = 1)        
    users = Array.new
    count.times.and_return do # <== something like this
      users += get_users_online
    end
  end  
役に立ちましたか?

解決

#tapをチェックしてください。それは「戻る」を行うための新しいファングルな方法です。

def find_users_online(count = 1)   
  [].tap do |users|
    count.times { users += get_users_online }
  end
end

他のヒント

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

count.times.map {get_users_online}.flatten

別のオプションはです 戻る ブロック

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

どうですか

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

?

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 }
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top