Guillermo Alvarez
Guillermo Alvarez

Reputation: 1775

Using each in Ruby

I am starting to learn ruby and am trying to figure out a way to if i have an array of 16 numbers, to print those numbers 4 at a time using only the each method. I can easily do this with a loop but i am lacking full understanding of the each method in Ruby so this gives me some trouble.

I have the following:

x=[*1..16]
index=0
x.each do |element|
  puts element[index]
  index=index+3
end

Now obviously this is completely wrong and i know that but i wanted to put something on here. A little advice would be great.

Thank you

Upvotes: 0

Views: 716

Answers (2)

Marek Příhoda
Marek Příhoda

Reputation: 11198

A possible solution:

a = (1..16)
a.each_slice(4) { |s| p s[3] }

EDIT: If you want print 4 elements on one line, then skip to the next line and print the next 4 elements, etc

a = (1..16)
a.each_slice(4) { |s| puts s.join(' ') }

Or using each only

a = (1..16)
a.each { |i| print i.to_s + ' '; print "\n" if i % 4 == 0 }

Upvotes: 6

undef
undef

Reputation: 445

Try each_slice http://ruby-doc.org/core-1.9.3/Enumerable.html#method-i-each_slice.

Using that would look something like

(1..16).each_slice(4) do |x|
  puts x.inspect
end

Upvotes: 2

Related Questions