简体   繁体   English

遍历数组并存储为新数组-Ruby

[英]Loop Through Array and Store as New Array - Ruby

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] 存储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 %>

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 %>

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. 有关更多列表操作,请参见http://www.ruby-doc.org/core-2.0/Array.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM