Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby: elegant array initialization and return in 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?

Like:

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 
like image 697
steve_gallagher Avatar asked Dec 05 '11 17:12

steve_gallagher


1 Answers

deltas.each_slice(2).flat_map do |dx, dy|
  [x + dx, y + dy]
end
like image 68
tokland Avatar answered Oct 03 '22 21:10

tokland