Vladimir Tsukanov
Vladimir Tsukanov

Reputation: 4459

Ruby - exit from IF block

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?

Upvotes: 19

Views: 42603

Answers (3)

psychoslave
psychoslave

Reputation: 3031

Instead of if, you can use a while loop that never actually loop, and put breaks wherever fits your need.

while some·condition
  something·likely
  break unless some·additional·condition
  something·less·likely
  break
end

Upvotes: 0

tadman
tadman

Reputation: 211540

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.

Upvotes: 21

coreyward
coreyward

Reputation: 80041

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

Upvotes: 2

Related Questions