1

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.

5 Answers 5

2

try each_with_index

emails.each_with_index do |email, index|

  if index == 0
    # do something
  end 

end
Sign up to request clarification or add additional context in comments.

1 Comment

Although I understand where people are coming from with the enumeration, this answer is what I was after. Thank you all
1

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]

Comments

1

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

Comments

0

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

1 Comment

I think index will start from 0.
0

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.

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.