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
···
--
Posted via http://www.ruby-forum.com/.
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
--
Posted via http://www.ruby-forum.com/.
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.
On Thu, Dec 5, 2013 at 7:49 AM, Raja gopalan <lists@ruby-forum.com> wrote:
hi,
Can I use each loop to print alternative element without giving any 'if
condition' inside the loopa=[1,2,3,4,5]
output would be
2
4
5
hi Jesus.
you are right, 5 should not be there, I made a mistake and gave the code
which i expected, thank you.
--
Posted via http://www.ruby-forum.com/.
hi Robert Klemme
Thank you, that's an another beautiful way.
RAJ
--
Posted via http://www.ruby-forum.com/.
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
On Thu, Dec 5, 2013 at 9:38 AM, Raja gopalan <lists@ruby-forum.com> wrote:
you are right, 5 should not be there, I made a mistake and gave the code
which i expected, thank you.
--
remember.guy do |as, often| as.you_can - without end
http://blog.rubybestpractices.com/