0

This is simple but I can't find anything. I have an array that I want to loop through, pull up a specific attribute for each, and then store those attributes in a new array.

Basically:

  • store array2 = [Array1[0].attr, Array1[2].attr, Array1[3].attr]

What I have

<% storedArray = [] %>
<% @data = current_user.data_items %>
       <% @data.each do |data_item| %>
          <% storedArray[data_item.count] = data_item.url_metric.da %>
       <% end %>

Updated:

I got it to work but in a really bad way. Suggestions?

<% array = []; i = 0 %>

   <% @data = current_user.reports[0].data_items %>
   <% @data.each do |data_item| %>
      <% array[i] = data_item.url_metric.da %>
      <% i = i+1 %>
   <% end %>
   <%= array %>

2 Answers 2

1

Check out the method collect

It returns a new array with the values created after the loop through the source array. In your problem the code would be:

# Get initial array
<% @data_items = current_user.reports[0].data_items %>

# Iterate through original array and return value to new array
<% @array = @data_items.collect do | data_item | %>
    # Process item
    <% data_item.url_metric.da %>
<% end %>

# Now your new array is ready to go.
<%= @array %>
Sign up to request clarification or add additional context in comments.

Comments

0

Use

<% @array= current_user.data_items.map {|data_item| data_item.url_metric.da} %>

You can directly use the resulting array by using each like the following:

<% current_user.data_items.map {|data_item| data_item.url_metric.da}.each |result| %>
# Do something with the result
<% end %>

See http://www.ruby-doc.org/core-2.0/Array.html for more list operations.

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.