Tim Higgins Tim Higgins - 1 year ago 80
Ruby Question

each_with_index condition statement ruby

I am a programming neophyte so I apologize if this is more simple than it seems. I've searched around and only found individual answers for each_with_index and conditions, never together.

My goal is to iterate through an array and perform a single action based on the index. My first draft looked a little something like this:

@word_array.each_with_index do |word, index|
if index % 2 == 0
word = "EVEN"

Which works, but then I wanted to refactor it into a single line. My first attempt invoked an error due to it anticipating the else
part of the condition:

@word_array.each_with_index { |word, index| index % 2 == 0 ? word = "EVEN" }

I had tried it this way first thinking I may have some luck being as the block did not require an
condition, but obviously to no avail. I did discover I could use
as a placeholder and have the code work:

@word_array.each_with_index { |word, index| index % 2 == 0 ? word = "EVEN" : nil }

However even after further reading up on each piece I'm uncertain whether or not having the
there could potentially cause troubles in more complex situations even though it doesn't hamper my basic example here.

So to break it down into two questions:

1.) Is the
going to bite me in the butt later?

2.) If so, is there a way to go about this using one line, or is my best bet to stick with the conditional block?

Answer Source

If you want this one-liner style:

word = 'EVEN' if index % 2 == 0

Using a ternary with a missing condition leaves people wondering why you didn't do this in the first place. A ternary is a great way to branch, like:

(index % 2 == 0) ? 'EVEN' : word
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download