in Hacking, misc

Ruby remove ternary conditions

Somethimes you want to do something conditionally depending on a boolean.
(I don't like the double question mark in ternary-if)

For example:

# add a class to an element
tag.div(class: selected? ? "sample" : nil)

# executing code conditionaly:
if selected? 
    #.. code
end

This code could be rewritten like this:

# add a class to an element
tag.div(class: selected? { "sample" })

# executing code conditionaly: (this could be done, no per se an improvement)
selected? do
    #.. code
end

To use the construct above, give the boolean operation the following content.

  • if a block is given and the condition is true it invokes the block else it returns nil
  • if no block is given, the boolean is returned
def selected?
    return selected? ? yield : nil if block_given?
    @selected
end

:-)