Ruby: elegant array initialization and return to Ruby

I have a method:

def deltas_to_board_locations(deltas, x, y) board_coords = [] deltas.each_slice(2) do |slice| board_coords << x + slice[0] board_coords << y + slice[1] end board_coords end 

where deltas is an array and x, y are fixnums.

Is there a way to eliminate the first and last line to make the method more elegant?

how

 def deltas_to_board_locations(deltas, x, y) deltas.each_slice(2) do |slice| board_coords << x + slice[0] board_coords << y + slice[1] end end 
+6
source share
3 answers
 deltas.each_slice(2).flat_map { |dx, dy| [x + dx, y + dy] } 

The above works for Ruby 1.9, but I agree with Renault. The obvious solution should be preferred, in which case it is faster than mine.

Change @Tokland comments included.

+4
source
 deltas.each_slice(2).flat_map do |dx, dy| [x + dx, y + dy] end 
+7
source
 deltas.each_with_index.map { |val, idx| val + (idx % 2 == 0 ? x : y )} 

Regardless of whether it is โ€œless complexโ€, it depends on the audience.


Reducing duplication and complexity should focus on macro behavior, rather than micro-refactoring short, readable methods.

Will this rewrite lead to a qualitatively more understandable system? Or are there more important issues of a higher level?

Is the improvement of documentation for applications, classes, and methods improved? Should these documents be in code or on a wiki? Will a picture cost a thousand lines?


Comparison of performance against @tokland (its gain is a significant amount). Assuming deltas is an array of a million elements 1-1 m in size. MRI, Ubuntu, an old pokey machine.

My version

 deltas.each_with_index.map { |val, idx| val + (idx % 2 == 0 ? x : y )} Total: 1.764807 %self total self wait child calls name 100.00 1.76 1.76 0.00 0.00 1 Array#each 0.00 1.76 0.00 0.00 1.76 1 Global#[No method] 0.00 1.76 0.00 0.00 1.76 2 Enumerable#each_with_index 0.00 1.76 0.00 0.00 1.76 1 Enumerable#map 0.00 1.76 0.00 0.00 1.76 1 Enumerator#each 

A better, shorter, more communicative version

 deltas.each_slice(2).flat_map { |dx, dy| [x + dx, y + dy] } Total: 1.236144 %self total self wait child calls name 100.00 1.24 1.24 0.00 0.00 1 Array#each 0.00 1.24 0.00 0.00 1.24 1 Global#[No method] 0.00 1.24 0.00 0.00 1.24 2 Enumerable#each_slice 0.00 1.24 0.00 0.00 1.24 1 Enumerable#flat_map 0.00 1.24 0.00 0.00 1.24 1 Enumerator#each 

Original version (fastest):

 Total: 0.899122 %self total self wait child calls name 100.00 0.90 0.90 0.00 0.00 1 Array#each 0.00 0.90 0.00 0.00 0.90 1 Global#[No method] 0.00 0.90 0.00 0.00 0.90 1 Enumerable#each_slice 
+6
source

Source: https://habr.com/ru/post/903130/


All Articles