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?
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.
def will_parse?(obj); !obj.nil? && obj.respond_to?(:parse) && obj.is_ready_and_willing?; end&&= is the binary-and equivalent of ||=, so a &&= b is the same as a && a = b. So if a is truthy, then the value of b is assigned to a.should_do_x? instead of a pile of complicated logic is a great way to do it, but in this case it's not clear how much logic there is.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 true then block.call end then it would workblock)? I think the syntax requires it to be &block if you're using it in place of an explicit block.