In IF block i need to check if some condition true and if it does, exit from block.
#something like this
if 1 == 1
return if some_object && some_object.property
puts 'hello'
end
How can i do it?
In Ruby, we use a break statement to break the execution of the loop in the program. It is mostly used in while loop, where value is printed till the condition, is true, then break statement terminates the loop. In examples, break statement used with if statement. By using break statement the execution will be stopped.
To break out from a ruby block simply use return keyword return if value.
It tells Ruby to skip that particular number (abort that particular loop repetition at this point) and move on to the next one (which will be odd, so that's why it prints the odd numbers). Submitted by Alex J.
You can't break out of an if
like that. What you can do is add a sub-clause to it:
if (cond1)
unless (cond2)
# ...
end
end
If you're having problems with your logic being too nested and you need a way to flatten it out better, maybe what you want to do is compute a variable before hand and then only dive in if you need to:
will_do_stuff = cond1
will_do_stuff &&= !(some_object && some_object.property)
if (will_do_stuff)
# ...
end
There's a number of ways to avoid having a deeply nested structure without having to break
it.
Use care in choosing the words you associate with things. Because Ruby has blocks, I'm not sure whether you're under the impression that a conditional statement is a block. You can't, for example, do the following:
# will NOT work:
block = Proc.new { puts "Hello, world." }
if true then block
If you need to have a nested conditional, you can do just that without complicating things any:
if condition_one?
if condition_two?
# do some stuff
end
else
# do something else
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With