Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to return true if one statement in a block returns true in Ruby?
    text
    copied!<p>Is it possible to create a method in Ruby that takes a block and runs each statement in the block until one of them returns false?</p> <pre><code>done = prepare_it do |x| method_1 method_2 method_3 end puts "Something did not work" unless done </code></pre> <p>I wanted the function prepare_it to run each statement but if one of them fails, the function quits. If the function returns true, it means that all steps were successful.</p> <p>This seems to be calling for an Exception, but I'm not sure how to trigger and process it. I wish I did not have to modify the method_x functions to throw an Exception upon failure, but rather make prepare_it throw the exception if one of the method_x fails (returns false)</p> <p><strong>Edit:</strong> Thanks for the suggestions, I think I need to add more details to my question. This is my first stab at metaprogramming and creating a DSL. :)</p> <p>I have a class to send commands to a router. There are many steps that always need to be executed in sequence (connect, login, pass, etc). I thought it would be nice to give the user the ability to change the order of the commands if they wish to do so. For example, some routers don't ask for a user and go directly to the password prompt. Others skip the login altogether. In some cases you need to elevate the privilege or set terminal options.</p> <p>However, there should be a mechanism to fail the entire block if any of the commands failed. So, if for some reason the password failed (the method returns false/nil), it makes no sense to continue with the rest of the commands. And I should flag it that something failed.</p> <p>The &amp;&amp; method works, but I don't think it would be a nice interface.</p> <p>Maybe instead of getting a big block, maybe I should force users to give me smaller blocks, one at a time, which are put in a stack and a run command yields then one by one?</p> <pre><code>my_router.setup do {send_pass} my_router.setup do {set_terminal} my_router.setup do {enable_mode} my_router.run_setup </code></pre> <p>I think it would be super cleaner if I could do</p> <pre><code>my_router.setup do |cmd| cmd.send_pass cmd.set_terminal end puts "Done" if my_router.ready? </code></pre> <p>So any magic trickery that happens behind the scene is welcome! :)</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload