Ctpelnar1988 Ctpelnar1988 - 5 months ago 14
Ruby Question

How to get rid of array after .each method

I am instantiating a variable like so:

Searches Controller:

@search_results = Business.near(params[:search_zip], params[:radius]).to_a


Searches View

<%= @search_results.map do |sr| %>
<%= sr.business_name %>
<% end %>

=> PetStore FoodStore BeautyStore ClothingStore ["\n", "\n", "\n", "\n"]`


How can I get rid of the array at the end?

Answer

The array is printed because you are using <%= instead of <%. Change

<%= @search_results.map do |sr| %>
  <%= sr.business_name %>
<% end %>

to

<% @search_results.map do |sr| %>
  <%= sr.business_name %>
<% end %>

map returns the evaluation of the block. The returned value is then printed because of <%=.

Also note you don't need a map, each is sufficient and will save you resources in this case:

<% @search_results.each do |sr| %>
  <%= sr.business_name %>
<% end %>