Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 702
Vladimir Tsukanov Avatar asked Oct 19 '11 16:10

Vladimir Tsukanov


People also ask

How do you exit an if statement in Ruby?

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.

How do you exit a block in Ruby?

To break out from a ruby block simply use return keyword return if value.

What is next if in Ruby?

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.


2 Answers

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.

like image 197
tadman Avatar answered Sep 28 '22 07:09

tadman


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
like image 26
coreyward Avatar answered Sep 28 '22 07:09

coreyward