HiveBrain v1.2.0
Get Started
← Back to all entries
patternrubyMinor

Hide content unless an array contains at least one non-empty string

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
unlessnonarrayemptyonecontainsleastcontentstringhide

Problem

I have an array of hints. Sometimes, this array could contain an empty string. Occasionally, the array might contain only empty strings, in which case I want the whole block to be skipped. This is what I came up with:


    
        Please observe the following hints:

        
        
            
                
            
        
        

        
    


An example of @hints:

["", "", "Have you tried turning it off and on again?"]


Or:

[""]


Anyone know a better way?

Solution

As @tokland pointed out, your current code has one too many loops really.

As for checking if all the strings are empty, you have some options.

1) The any? method accepts a block, so you can test if any of the elements in an array match a certain condition. In your case, you could do

@hints.any? { |string| string.present? }


since present? checks if a string is non-empty. But you can also shorten that to just

@hints.any?(&:present)


With that you could do something like


    Please observe the following hints:

    
    
        
            
        
    
    


2) Alternatively, and I'd say nicer, you can filter the array beforehand, to simply not include blank strings using select or, conversely, reject.

@hints = some_hints.reject(&:blank?)   # reject blank strings
# or...
@hints = some_hints.select(&:present?) # keep non-blank strings


This should happen in the controller when you first set @ hints (or even earlier - don't know where the hints come from, but there's little need to keep empty strings around if you don't have to, so either strip them out early, or just avoid adding them to begin with).

With a "clean" @hints array you can do this:


    Please observe the following hints:

    
    
        
    
    

Code Snippets

@hints.any? { |string| string.present? }
@hints.any?(&:present)
<% if @hints.any?(&:present) %>
    <p>Please observe the following hints:</p>

    <ul>
    <% @hints.each do |hint| %>
        <% unless hint.empty? %>
            <li><%= hint %></li>
        <% end %>
    <% end %>
    </ul>
<% end %>
@hints = some_hints.reject(&:blank?)   # reject blank strings
# or...
@hints = some_hints.select(&:present?) # keep non-blank strings
<% unless @hints.empty? %>
    <p>Please observe the following hints:</p>

    <ul>
    <% @hints.each do |hint| %>
        <li><%= hint %></li>
    <% end %>
    </ul>
<% end %>

Context

StackExchange Code Review Q#68369, answer score: 2

Revisions (0)

No revisions yet.