0

I am writing a helper method for my rails views. After evaluating each value in an array I want to output a button to the html. However, 'puts' is not working and 'return' will work only for one value and end the operator there only.

def show_power_buttons
    levels = [1, 2, 3, 4, 5]

    levels.each do |level|
        count = @player.powers.where(level: level).count
        if count > 0
            puts (link_to level, '#', :class => 'btn btn-primary')
        end
    end
end

I know I am missing something very obvious but unable to figure it out.

2 Answers 2

3

each returns array on which you have called it, it does not return result of the block.

You can use map to make this work

def show_power_buttons
  levels = [1, 2, 3, 4, 5]

  levels.map do |level|
    count = @player.powers.where(level: level).count        
    (link_to level, '#', :class => 'btn btn-primary') if count > 0
  end.compact.join('\n').html_safe
end

compact will discard all nil values, we then use join because this is still array, you can join it or can use it this way and in your view just say:

def show_power_buttons
  levels = [1, 2, 3, 4, 5]

  levels.map do |level|
    count = @player.powers.where(level: level).count        
    (link_to level, '#', :class => 'btn btn-primary') if count > 0
  end.compact # returns array of string that are links
end

<%= show_power_buttons.each do |pw| %>
  <%= pw.html_safe %>
<% end %>

You have to use html safe, because it will convert string to html

Sign up to request clarification or add additional context in comments.

3 Comments

Yes, you are right I'll have to use html_safe. Any reason to use 'map' over pushing directly to array like in the other answer?
map is more cleaner, because it is meant for this. Map array that it contains the element you desire ruby-doc.org/core-2.2.0/Array.html#method-i-map
@Hacktacus you don't need to initialize and fill array manually. Why do you ever want to use 2 variables, when 1 is enough?
1

Collect the return value and return it at the end of the method:

def show_power_buttons
    levels = [1, 2, 3, 4, 5]
    retval = []
    levels.each do |level|
        count = @player.powers.where(level: level).count
        if count > 0
            retval << link_to level, '#', :class => 'btn btn-primary'
        end
    end
    return retaval 
end

It will output the arrach of links.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.