Reputation: 67
I have a collection:
@monday = HomeTask.where(:class_room => current_user.class_room, :day => 'Понеділок').order(created_at: :desc)
The @monday
variable contains data from the database. In view, I show all dates from the collection:
<% @monday.each_with_index do |mnd, i| %>
<% if mnd.data == mnd.data[i + 1] %>
<%= link_to 'nice' %>
<% else %>
<%= link_to 'ohhh...' %>
<% end %>
<% end %>
Within if
body, I want to refer to the next element. But it does not work. In C++, to refer to the next element in the first iteration, it would be coded like this:
if(array[i] == array[i+1])
How do I use each
in Ruby?
Upvotes: 1
Views: 374
Reputation: 5552
What if you could go with following changes,
- <% if mnd.data == mnd.data[i + 1] %>
+ <% if @monday[i+1] != nil && mnd.data == @monday[i+1].data %>
Or simply,
- <% if mnd.data == mnd.data[i + 1] %>
+ <% if mnd.data == @monday[i+1].try(:data) %>
Upvotes: 0
Reputation: 110665
arr = [1,2,3,4,5,6,7,8]
enum = arr.to_enum
#=> #<Enumerator: [1, 2, 3, 4, 5, 6, 7, 8]:each>
loop { puts "%d : %d" % [enum.next, enum.peek] }
1 : 2
2 : 3
3 : 4
4 : 5
5 : 6
6 : 7
7 : 8
See Kernel#to_enum1, Kernel#loop, Enumerator#next and Enumerator#peek. peek
raises a StopIteration
exception when it is executed after the last element of arr
has been generated. loop
handles that exception by breaking out of the loop.
1. As to why this Kernel
instance method is documented as an Object
instance method, please see the second paragraph at the docs for Object.
Upvotes: 4
Reputation: 441
If you want to iterate an array and have access to more than one item in each iteration you can use each_cons
arr = [1,2,3,4,5,6,7,8]
arr.each_cons(2){|a,b|
puts "#{a} : #{b}"
}
# 1 : 2
# 2 : 3
# 3 : 4
# 4 : 5
# 5 : 6
# 6 : 7
# 7 : 8
Using each_cons you can easily compare two (or more) consecutive items of an array.
Upvotes: 6