John Joyce wrote:
I've seen this in Rails, but it is just ERb, so it is Ruby...
<%= link_to 'Previous page', { :page => @product_pages.current.previous
} if @product_pages.current.previous %>
I'm curious how it is different from this...
<%= if @product_pages.current.previous link_to ('Previous page', {
:page => @product_pages.current.previous })
end
%>
I've seen this kind of if statement reversal a few times now in Ruby
code. I call it do-if because it looks similar to do-while, but I am
curious if reversing the condition affects the interpreter's speed at
all. If they are the same, then isn't the standard if conditional better
for human legibility and understanding?
The first form of the statement is valid for only one instruction. Both
if something
do_something
end
and
do_something if something
are equivalent, but when it comes to
if a
one_thing
another_thing
end
you simply can't use the other form, as it applies to only one instruction.
The whole thing about this is readability. Depending on the cases and
your personal tastes, it will look more logical to use one form or
another (for one instruction). What is great in Ruby (IMHO), is that you
have many ways to express the same things, some of them quite verbose,
which means you can write code sometimes nearly as readable as pure
English text.
Cheers,
Vince
···
--
Vincent Fourmond, PhD student (not for long anymore)
http://vincent.fourmond.neuf.fr/