Zack Shapiro
Zack Shapiro

Reputation: 6998

Placing items in an array into div classes based on size of element

I have an array of things, things = [1, 500, 900, 0, -105, -8, 16, 4] and I want to display them in red, green or black in my view based on whether they're larger than zero, smaller than zero or equal to zero.

Right now my code looks like:

<%= @things.each do |p|%>
 <% if p > 0 %>
      <%= p  %>
    <% elsif p < 0 %>
      <%= p %>
    <% else %>
      <%= p %>
 <% end %>
<% end %>

I'm not displaying the numbers correctly to start, and I've gone through a few iterations of putting them in divs and nothing seems to work. Once I get 'em in classes, I can add colors pretty easily. (I also need to keep them in the same order they're in in the array)

Any help would be greatly appreciated.

Upvotes: 0

Views: 202

Answers (3)

az7ar
az7ar

Reputation: 5237

The first thing I can think of is build a view helper

def set_color number 
  case
    when number == 0 
       "black"
    when number > 0
       "green"
    when number < 0
       "red"
  end
end

and in the view

<% @things.each do |p|%>
<div class="<%= set_color(p)%>"> <%= p %> </div>
<% end %>

Finally do the CSS

Upvotes: 0

Anthony Alberto
Anthony Alberto

Reputation: 10395

Not sure what's the issue here

 <% @things.each do |p|
     if p < 0
       class_name = 'red'
     elsif p > 0 
       class_name = 'green'
     else 
       class_name = 'black'
     end %>
     <div class="<%=class_name%>"><%= p %></div> 
<% end %>

Then css :

.red{color:red;}
.green{color:green;}
.black{color:black;}

Edit : In your example, you were using <%= @things.each. Don't use <%= for things that are not supposed to output anything

Upvotes: 3

Phrogz
Phrogz

Reputation: 303224

If you want them grouped by positive/negative/0

<% @things.group_by{ |n| n<=>0 }.sort.each do |sign,items|%>
  <ul class="<%= sign==-1 ? 'negative' : sign==1 ? 'positive' : 'zero'%>">
    <% items.each do |item| %>
      <li><%= item></li>
    <% end %>
  </ul>
<% end %>

If you want them in array order, just classed

<ul>
  <% @things.each do |thing|
    css = case thing <=> 0
      when -1 then "negative"
      when  0 then "zero"
      when  1 then "positive"
    end
    %>
    <li class="<%=css%>"><%= thing %></li>
  <% end %>
</ul>

Note that you incorrectly have an equals sign at the start of your each wrapper:

<%= @things

...which will cause the to_s representation of the entire array to be output (you don't want that).

Upvotes: 0

Related Questions