Reputation: 1105
I have what will probably become a simple question to answer.
I have an array called emails
.
I'm iterating over them using emails.each do |email|
.
What I want to say is:
# if array index is 0, do this.
I've tried if email.index == 0
.
I've tried to find a solution, but can't for the life of me find it. As it's only one argument, I'd like to avoid a case statement.
Upvotes: 1
Views: 204
Reputation: 44
Ok. If you looking for index 0 - you can use emials[0]
or emails.at(0)
, or you can iterate emails -
emails.each_with_index do |val, index|
if index == 0
# something
end
end
It's all.
Upvotes: 0
Reputation: 4615
try each_with_index
emails.each_with_index do |email, index|
if index == 0
# do something
end
end
Upvotes: 2
Reputation: 66837
Like people said before, each_with_index
is a good choice. However, if you want to start your index from anything else than 0, there's a better way (note that the dot is on purpose, we are calling Enumerator#with_index
here):
emails.each.with_index(1) do |email, index|
# ...
end
Upvotes: 1
Reputation: 37
You can use .each_with_index
it will provide you the index of each element in the array.
for example
['a','b','c'].each_with_index {|item, index|
puts "#{item} has index #{index}"
}
output
a has index 0
b has index 1
c has index 2
Upvotes: 0
Reputation: 42192
Like the others answered, if you need the enumeration:
emails.each.with_index([startindex]) do |email, index|
eg
emails.each.with_index(1) do |email, index|
But if you only need that element then you can act upon directly like this
emails.first
what is the same as
emails[0]
Upvotes: 1