what is the best way to check condition and run method in Ruby? which one is most readable?
bar if foo
or
foo and bar
what is the best way to check condition and run method in Ruby? which one is most readable?
bar if foo
or
foo and bar
I would use one over the other depending on the situation.
If I am interested in running a method depending on a condition met (aka condition does not have a side effect):
do_something if this_condition_is_true
If I am interested in running a method only if another method finished successfully (aka both methods have side effects):
do_something and do_something_other
Edit As pointed out by Smar, the following may not be true for the newest Ruby versions. Checking right now. The issue continues here
spickermann provides a good answer, but its second case is not clear enough, so I will spell it out a more.
Usually, you should use if
as it is designed for that purpose.
bar if foo
But often, you want to define a local variable on the way of evaluating a condition. In that case, you cannot use the postfix if
notation; the following will raise an error (provided that x
is not defined prior):
bar(x) if x = h[:foo]
and you have to use and
if you want to put it on a single line.
x = h[:foo] and bar(x)