Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional blocks in Ruby

Tags:

ruby

Say I have function with_foo that takes a block, and wrap it around a piece of code, like

with_foo do
  puts "hello!"
end

Now I would like to make the wrapping conditional, like

if do_with_foo?
  with_foo do
    puts "hello!"
  end
else
  puts "hello!" # without foo
end

Is there any way to write this shorter/more elegantly, meaning without having to repeat the code puts "hello!"?

like image 517
zero-divisor Avatar asked May 24 '12 11:05

zero-divisor


People also ask

What are the conditional statements available in Ruby?

Here, we will explain all the conditional statements and modifiers available in Ruby. if expressions are used for conditional execution. The values false and nil are false, and everything else are true. Notice Ruby uses elsif, not else if nor elif.

What are the conditions in Ruby?

The conditions are generally of Boolean type and return either true or false as the result. Conditionals are formed using if or case with some comparison operators. A conditional assists data about where to move next. In Ruby, 0 is considered as true whereas in other programming languages it is considered false.

How do you use if statements in Ruby?

If something is true (the condition) then you can do something. In Ruby, you do this using if statements: stock = 10 if stock < 1 puts "Sorry we are out of stock!"

What is the difference between false and nil in Ruby?

The values false and nil are false, and everything else are true. Notice Ruby uses elsif, not else if nor elif. Executes code if the conditional is true. If the conditional is not true, code specified in the else clause is executed.


1 Answers

if you are willing to specify argument with a block, it is possible.

given with foo above, you can write such snippet:

whatever = proc {puts "hello"}
#build a proc object with a block
if do_with_foo?
  with_foo &whatever
#pass it to with_foo
else
  whatever.call
#normally call it
end
like image 127
Jokester Avatar answered Sep 28 '22 05:09

Jokester