user3399235
user3399235

Reputation: 247

For loop to access array elements of index

I am trying to compare the names of the element at the current index and the previous index for each element to determine if they are the same name so I don't print out the name twice.

Unfortunately, trying to access the array element using array[i] doesn't work, but if I hard-code an index or just print out the index, it works fine so I'm not sure where it's messing up.

I need to be able to access the previous element though so I can't use other loops so only suggest something where I can access the previous element in the array.

<% for i in 1..count %>
    <% if array[i].count > 1 %>
        <% if array[i-1].name == array[i].name %>
           <%= array[i].name %> 
           <%= array[7].name %> 
           <%= i %>     
    <% end %>
 <% end %>

Does anyone know the correct way to access an element in an array?

Upvotes: 1

Views: 1482

Answers (4)

Max Williams
Max Williams

Reputation: 32933

Just thought of another way of doing this:

grouped = array.group_by(&:name)

Now you have a hash where each key is a unique name and the corresponding value is all the array elements with that name. So next you can do stuff like

#list of names in alphabetical order
grouped.keys.sort

#get one element for each unique name
grouped.map{|name,els| els.first}

#print out how many you have for each name
grouped.each{|name, els| puts "#{name.inspect} => #{els.size} elements"};false 

Upvotes: 0

Brad
Brad

Reputation: 738

This should do it if your list is sorted and all you care about is printing names:

<% array.map(&:name).uniq.each do |name| %>
  <%= name %>
<% end %>

Upvotes: 2

Sharvy Ahmed
Sharvy Ahmed

Reputation: 7405

You can keep in mind that you are using Ruby, and the motto of Ruby is "Do More in Less Work".

You can use uniq to filter out all similar elements, then iterate through them to do whatever you want to do. uniq works like this:

a = [ "a", "a", "b", "b", "c" ]
a.uniq   # => ["a", "b", "c"]

This should do it all what you tried to do:

<% array.uniq.each do |obj| %>
  <%= obj.name %>
<% end %>

Upvotes: 0

Max Williams
Max Williams

Reputation: 32933

More generally, you can do it like this:

array.each_with_index do |el, i|
  prev_el = array[i-1]  #will be nil for the first element
  next_el = array[i+1]  #will be nil for the last element
  if prev_el && el.name == prev_el.name
    #name same as previous
  end
  if next_el && el.name == next_el.name
    #name same as next
  end
end

You should avoid index-based array access for loops, not because they don't work but because there are much nicer and more readable ways of looping through arrays in Ruby.

Upvotes: 1

Related Questions