2

Is it possible to call next from within a method for an outer loop:

bot.rb

while Option.daemon_active?(daemon: "bot")
  .....
  Trade.market_order
  ....
end

trade.rb

class Trade
  def self.market_order
     ... complex code ...
     response = exchange.market_sell
     next if response["state"] == false # This fails. This should start new iteration of while in bot.rb
  end
end

There is quite similar question, but it doesn't seem to suit me: call next on ruby loop from external method

Jonas
  • 121,568
  • 97
  • 310
  • 388
Ilya Cherevkov
  • 1,743
  • 2
  • 17
  • 47
  • 4
    What’s wrong with `next unless Trade.market_order` in the while block? – Aleksei Matiushkin Apr 21 '15 at 10:02
  • 1
    agreed with @mudasobwa the `Bot` should not be controlled via `Trade`, it is simply not its responsibility and increases coupling which usually should be avoided (hard to follow path of execution, hard to refactor, `Trade` may break if `Bot` changes etc.) – jethroo Apr 21 '15 at 10:07
  • Thank you @mudasobwa. Good comment, although right now market order is much more complicated than I shown here, there are lot of checks and all of them need to call next at some point. Maybe I need to simplify it – Ilya Cherevkov Apr 21 '15 at 10:11
  • `return false` everywhere you need the next iteration or use @sawa’s approach with `catch`. – Aleksei Matiushkin Apr 21 '15 at 10:12

1 Answers1

3

Yes. You should use throw and catch.

bot.rb

while Option.daemon_active?(daemon: "bot")
  catch(:foo) do
    ...
    Trade.market_order
    ...
  end
end

trade.rb

class Trade
  def self.market_order
    ...
    response = exchange.market_sell
    throw :foo if response["state"] == false
  end
end
sawa
  • 165,429
  • 45
  • 277
  • 381