Each loop question

hi,

Can I use each loop to print alternative element without giving any ‘if
condition’ inside the loop

a=[1,2,3,4,5]

output would be
2
4
5

On Thu, Dec 5, 2013 at 7:49 AM, Raja gopalan [email protected]
wrote:

5
I don’t understand the logic. If you want to skip one element each
time in the loop, the 5 would not be there, so if you could clarify
the requirements, we could help you better. To skip one element and
print only the even indexes you could do this:

2.0.0p195 :004 > a = (1…10).to_a
=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
2.0.0p195 :005 > a.each_slice(2) {|odd,even| puts even}
2
4
6
8
10

Jesus.

hi Jesus,

you are right, 5 should not be there, I made a mistake and you gave the
code which i had expected, thank you.

On Thu, Dec 5, 2013 at 9:38 AM, Raja gopalan [email protected]
wrote:

you are right, 5 should not be there, I made a mistake and gave the code
which i expected, thank you.

We can even get away completely without block:

irb(main):006:0> puts 2.step(5, 2).to_a
2
4
=> nil

Kind regards

robert

hi Robert K.

Thank you, that’s an another beautiful way.

RAJ

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs