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

4
  • 4
    What’s wrong with next unless Trade.market_order in the while block? Commented Apr 21, 2015 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.) Commented Apr 21, 2015 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 Commented Apr 21, 2015 at 10:11
  • return false everywhere you need the next iteration or use @sawa’s approach with catch. Commented Apr 21, 2015 at 10:12

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

5 Comments

It seems you are overdesigned this. response["state"] ? response : nil as a return value from market_order and next unless market_order do the trick in a way more readable manner.
@mudasobwa That is not equivalent to the OP's code. false and nil are different.
Occasionally it is. OMG. response["state"] != false ? response : false.
next unless market_order may work, but that is not what OP asked. I agree with you that this may be an XY-question.
This is exactly what OP asked. Furthermore, this is exactly what your code does.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.