0

I have the following 7 lines of code, how can i made them shorter and less wordy?

max_group_size = 0
wrong_services.each do |service|
  group_size = service.iep_service.group_size
  if group_size > max_group_size then
    max_group_size = group_size
  end
end
junky
  • 1,480
  • 1
  • 17
  • 32

2 Answers2

5
max_group_size = wrong_services.map {|service| service.iep_service.group_size }.max
unnu
  • 744
  • 1
  • 5
  • 13
2
max_group_size = wrong_services.max_by{|service| service.iep_service.group_size}.iep_service.group_size

(Editted after comments)

steenslag
  • 79,051
  • 16
  • 138
  • 171
  • I liked both this and unnu's .map approach. I finally chose to accept this one because i like the max_by being nearewr the start of the line and easier to read for "what's going to happen". It would be great to know if there are performance differences between the two approaches. – junky Sep 24 '12 at 20:30
  • @Junky The solution with `map{...}.max` iterates over `wrong_services` and creates an intermediate nameless array with all sizes; then it iterates over it to get the maximum. The `max_by` does the same as your code: one iteration, keeping score of the maximum. I think this one should be faster, but I've been surprised before. I suggest you measure it yourself using your data; Ruby ships with the [benchmark](http://www.ruby-doc.org/stdlib-1.9.3/libdoc/benchmark/rdoc/Benchmark.html) module. – steenslag Sep 24 '12 at 21:26
  • 1
    This will give `service`, not `group_size`. – sawa Sep 25 '12 at 06:01
  • @sawa is correct. This will return the `wrong_service` with the max group size. [Ruby API Doc Enumerable#max_by](http://ruby-doc.org/core-1.9.3/Enumerable.html#method-i-max_by) – unnu Sep 25 '12 at 08:23