Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

Working through Day 2 of Ruby in "7 Languages in 7 Weeks" - the answer to the second question seems acceptable, the first one feels quite wrong. Any suggestions?

  1. Print the contents of an array of sixteen numbers, four numbers at a time, using just each.

    group = 0
    
    (1..16).each do |x| 
        print x
        group = group + 1
        if group % 4 == 0
            puts
            group = 0
        end
    end
    
  2. Now, do the same with each_slice in Enumerable (copied directly from http://ruby-doc.org/core-1.9.3/Enumerable.html#method-i-each_slice)

    (1..16).each_slice(4) {|x| p x}
    
share|improve this question
1  
(1..16) is not an array. Besides using each, the first solution uses print and puts from the Kernel class, and % and +from Numeric. This book is not for me. –  steenslag Feb 28 '12 at 22:55
    
steenslag: Those are just my attempts at answers :) Could you clarify your point a bit more perhaps with an example? –  Jedidja Mar 1 '12 at 18:02

1 Answer 1

up vote 5 down vote accepted

No need to save group x already saving it.

(1..16).each do |x|
  print x
  puts if x % 4 == 0
end
share|improve this answer
    
Oh geez. facepalm –  Jedidja Feb 28 '12 at 21:52
    
ruby style block arguments is coming strange to other language users. –  Selman Ulug Feb 28 '12 at 21:55
    
That is not a right answer, try with array of random number... –  rkj Jul 10 '13 at 21:27

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.