26

I try to clean my Code. The first Version uses each_with_index. In the second version I tried to compact the code with the Enumerable.inject_with_index-construct, that I found here.

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

.. .inject(groups) do |group_container, (element,index)|

but they are necessary

  • What is the use of these brackets?
  • How can I make the code clear and readable?

FIRST VERSION -- WITH "each_with_index"

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) # => [[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 } # => [ [[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] << element
    end

    groups
  end
end

SECOND VERSION -- WITH "inject" AND index

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] << element
      group_container
    end
  end
end
1

5 Answers 5

36

What is the use of these brackets?

It's a very nice feature of ruby. I call it "destructuring array assignment", but it probably has an official name too.

Here's how it works. Let's say you have an array

arr = [1, 2, 3]

Then you assign this array to a list of names, like this:

a, b, c = arr
a # => 1
b # => 2
c # => 3

You see, the array was "destructured" into its individual elements. Now, to the each_with_index. As you know, it's like a regular each, but also returns an index. inject doesn't care about all this, it takes input elements and passes them to its block as is. If input element is an array (elem/index pair from each_with_index), then we can either take it apart in the block body

sorted.each_with_index.inject(groups) do |group_container, pair|
  element, index = pair

  # or
  # element = pair[0]
  # index = pair[1]

  # rest of your code
end

Or destructure that array right in the block signature. Parentheses there are necessary to give ruby a hint that this is a single parameter that needs to be split in several.

Hope this helps.

0
20
lines = %w(a b c)
indexes = lines.each_with_index.inject([]) do |acc, (el, ind)|
  acc << ind - 1 if el == "b"
  acc
end

indexes # => [0]
1

In case, someone is here from 2013+ year, you have each_with_object and with_index for your needs:

records.each_with_object({}).with_index do |(record, memo), index|
  memo[record.uid] = "#{index} in collection}"
end
0

What is the use of these brackets?

To understand the brackets, first you need to understand how destruction works in ruby. The simplest example I can think of this this:

1.8.7 :001 > [[1,3],[2,4]].each do |a,b|
1.8.7 :002 >     puts a, b
1.8.7 :003?>   end
1
3
2
4

You should know how each function works, and that the block receives one parameter. So what happens when you pass two parameters? It takes the first element [1,3] and try to split (destruct) it in two, and the result is a=1 and b=3.

Now, inject takes two arguments in the block parameter, so it is usually looks like |a,b|. So passing a parameter like |group_container, (element,index)| we are in fact taking the first one as any other, and destructing the second in two others (so, if the second parameter is [1,3], element=1 and index=3). The parenthesis are needed because if we used |group_container, element, index| we would never know if we are destructing the first or the second parameter, so the parenthesis there works as disambiguation.

9In fact, things works a bit different in the bottom end, but lets hide this for this given question.)

5
  • I think each_slice will not work for me because with each_slice the last slice or group can be much smaller then the other groups and I need groups with almost the same size.
    – ovhaag
    May 6, 2013 at 19:35
  • @ovhaag [1, 8, 7, 5, 4, 2, 3, 8].sort.each_slice(3) results in [[1, 2, 3], [4, 5, 7], [8, 8]] , that is your test case. Can you give me an example that not work, and then I can improve my answer?
    – fotanus
    May 6, 2013 at 19:45
  • [1, 2, 3, 4, 5, 6, 7].sort.each_slice(3) # =>[[1, 2, 3], [4, 5, 6], [7]] not ok, last group too small [1, 2, 3, 4, 5, 6, 7].sort.each_slice(2) # =>[[1, 2], [3, 4], [5, 6], [7]] -- not ok, too many groups wanted: [1, 2, 3, 4, 5, 6, 7].in_groups(3) # => [[1, 2, 3], [4, 5], [6, 7]] -- ok 3 groups, size of biggest group - size of smallest group = 1
    – ovhaag
    May 6, 2013 at 20:55
  • The slice size should be the population size divided by number of groups (also self is gratuitous): sort.each_slice((size.to_f/number_of_groups).ceil).to_a
    – dbenhur
    May 6, 2013 at 21:47
  • @ovhaag Testing dbenhur tip also didn't worked for your last example. I'll remove the code from my answer to don't let it wrong, because I can't think in a better way to do it.
    – fotanus
    May 6, 2013 at 22:31
0

Seems like there already some answers given with good explanation. I want to add some information regards the clear and readable.

Instead of the solution you chose, it is also a possibility to extend Enumerable and add this functionality.

module Enumerable
  # The block parameter is not needed but creates more readable code.
  def inject_with_index(memo = self.first, &block)
    skip = memo.equal?(self.first)
    index = 0
    self.each_entry do |entry|
      if skip
        skip = false
      else
        memo = yield(memo, index, entry)
      end
      index += 1
    end
    memo
  end
end

This way you can call inject_with_index like so:

# m = memo, i = index, e = entry
(1..3).inject_with_index(0) do |m, i, e|
  puts "m: #{m}, i: #{i}, e: #{e}"
  m + i + e
end
#=> 9

If you not pass an initial value the first element will be used, thus not executing the block for the first element.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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