开发者

Doing each in Ruby, how to place a br every n items

Given I have 10 items to iterate and I want to place a br every 3 of them like this example. How can 开发者_JAVA技巧I do this in Ruby?

1
2
3
<br>
4
5
6
<br>
7
8
9
<br>
10


Solution 1

(1..10).each_slice(3){|a| puts '<br>' unless a[0] == 1; puts a}

Solution 2 (ruby 1.9.2)

(1..10).chunk{|i| i.%(3).zero?}.each{|r, a| puts(a, *('<br>' if r))}

Solution 3

puts (1..10).each_slice(3).map{|a| a.unshift('<br>')}.flatten.drop(1)

Solution 4 (ruby 1.9.2)

puts ['<br>'].product((1..10).each_slice(3).to_a).flatten.drop(1)

Solution 5

puts (1..10).each_slice(3).with_object([]){|a, aa| aa.push('<br>', *a)}.drop(1)

Solution 6

puts (1..10).map{|i| i.%(3).zero?? [i, '<br>'] : i}

Solution 7 (ruby1.9.2)

puts (1..10).to_a.
  tap{|a| a.length.downto(1){|i| a.insert(i, '<br>') if i.%(3).zero?}}


 (1..10).each do |i|
   puts i
   puts '<br>' if i % 3 == 0
 end


>> (1..10).each_slice(3).to_a.map{|x|x.join("\n")}.join("\n<br>\n")
=> "1\n2\n3\n<br>\n4\n5\n6\n<br>\n7\n8\n9\n<br>\n10"


If I understood the question well, he didn't say that the elements would always be (1..10), and most answers I saw here are only valid for this specific case, since they rely on the value of the element, not in the index. A more generic solution that would work not only when array = (1..10).to_a, but with any array of any size is this:

array.each_with_index do |o, i| 
  puts o
  puts '<br>' if i % 3 == 2
end


(1..10).each do |i| 
    puts i
    if (i % 3 == 0) 
      puts "<br/>"
    end
end


For printing, I like a combination of kurumi's and DigitalRoss's:

array.each_slice(3) {|elems| puts elems.join("\n"), '<br>' }

It's pretty declarative and very straightforward.


puts(
  (1..10)
  .each_with_index
  .map { |s, i| i % 3 == 2 ? [s, '<br>'] : s }
  .flatten
  .map(&:to_s)
  .join("\n")
)
  • This doesn't depend on the initial values being integers.
  • #each_with_index() with no block returns a generator, which means you can #map the results.
  • #flatten is used to move the '<br>' back in-line. You could just modify the string s instead like this: "#{s}#{i % 3 == 2 ? "\n<br>" : nil}" if you don't like the #flatten or you can't #flatten for some reason (e.g. you are using nested arrays already).
  • The final #map is to make sure everything is a string before joining. If you get rid of the #flatten as mentioned above, then you don't need this.


Something not so ruby-esque

k = 3
while k < array.size
    arrays.insert(k,"<br />")
    k += 4
end
p array


I would suggest do a for(i=0;i<length;i++) { if (i%3) //put br }

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜