Note that there are some explanatory texts on larger screens.

plurals
  1. PORuby inject with index and brackets
    primarykey
    data
    text
    <p>I try to clean my Code. The first Version uses <code>each_with_index</code>. In the second version I tried to compact the code with the <code>Enumerable.inject_with_index-construct</code>, that I found <a href="http://www.ruby-forum.com/topic/934794">here</a>.</p> <p>It works now, but seems to me as obscure as the first code. Add even worse I don't understand the brackets around element,index in</p> <pre><code>.. .inject(groups) do |group_container, (element,index)| </code></pre> <p>but they are necessary</p> <ul> <li>What is the use of these brackets?</li> <li>How can I make the code clear and readable?</li> </ul> <h2>FIRST VERSION -- WITH "each_with_index"</h2> <pre><code>class Array # splits as good as possible to groups of same size # elements are sorted. I.e. low elements go to the first group, # and high elements to the last group # # the default for number_of_groups is 4 # because the intended use case is # splitting statistic data in 4 quartiles # # a = [1, 8, 7, 5, 4, 2, 3, 8] # a.sorted_in_groups(3) # =&gt; [[1, 2, 3], [4, 5, 7], [8, 8]] # # b = [[7, 8, 9], [4, 5, 7], [2, 8]] # b.sorted_in_groups(2) {|sub_ary| sub_ary.sum } # =&gt; [ [[2, 8], [4, 5, 7]], [[7, 8, 9]] ] def sorted_in_groups(number_of_groups = 4) groups = Array.new(number_of_groups) { Array.new } return groups if size == 0 average_group_size = size.to_f / number_of_groups.to_f sorted = block_given? ? self.sort_by {|element| yield(element)} : self.sort sorted.each_with_index do |element, index| group_number = (index.to_f / average_group_size).floor groups[group_number] &lt;&lt; element end groups end end </code></pre> <h2>SECOND VERSION -- WITH "inject" AND index</h2> <pre><code>class Array def sorted_in_groups(number_of_groups = 4) groups = Array.new(number_of_groups) { Array.new } return groups if size == 0 average_group_size = size.to_f / number_of_groups.to_f sorted = block_given? ? self.sort_by {|element| yield(element)} : self.sort sorted.each_with_index.inject(groups) do |group_container, (element,index)| group_number = (index.to_f / average_group_size).floor group_container[group_number] &lt;&lt; element group_container end end end </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload