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!"
?
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.
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.
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!"
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.
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
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