Ruby:带有并发循环的哈希赋值

时间:2011-12-02 23:30:51

标签: ruby arrays hash iteration parallel-assignment

说我有一个数组:

array = [6, 6, 6, 4, 4, 6, 4, 4]

我有另一个字符串数组:

quadrant = ["upper_left", "upper_right", "lower_left", "lower_right"]

我有一个8 x 8 2-d数组,由电路板位置(@board)组成,它们是nil或Checker对象。

我的目标是创建一个哈希:

hash = { "upper_left" => @board[array[0]][array[1]] ,
         "upper_right" => @board[array[2]][array[3]] ,
         "lower_left" => @board[array[4]][array[5]] ,
         "lower_left" => @board[array[6]][array[7]] }

我有以下代码:

jump_positions = {}
QUADRANTS.each do |quad|
        array.each_slice(2) do |coord|
          jump_positions[quad] = @board[coord[0]][coord[1]]
        end

然后测试:

it "should assign board locations as adjacent positions and deliver that info as a whole" do
    @bs.board = board.create_board
    x_coord = 3
    y_coord = 1
    jump_assignments = @bs.assign_adjacent_positions(x_coord, y_coord)
    jump_assignments["upper_left"].class.should == nil
    jump_assignments["upper_right"].class.should == nil
    jump_assignments["lower_left"].class.should == Checker
    jump_assignments["lower_right"].class.should == Checker 
end

失败,因为所有的作业都属于'Checker'类,结果证明它们都是'Checker'对象。我知道这样做是因为循环是嵌套的,因此所有'quad'键都会初始化到最后一个板位置。

有没有办法可以在一次传递中使用'array'中的值为键分配值,以便正确分配它们?这个问题是否有意义?

2 个答案:

答案 0 :(得分:1)

我认为您只需要在other similar question的答案中添加一点map

hash = Hash[quadrant.zip(array.each_slice(2).map { |a| @board[a.first][a.last] })]

鉴于这样的董事会:

@board = [
    ['11', '12', ... '18'],
    ['21', '22', ... '28'],
    ...
    ['81', '82', ... '88']
]

上面的构造给了我hash这样的:

{
    "upper_left"  => "77",
    "upper_right" => "75",
    "lower_left"  => "57",
    "lower_right" => "55"
}

这似乎就是你要找的东西。

答案 1 :(得分:0)

mu太短让我重新考虑我的问题,我相信我的算法被打破了。实际上我最终将这种方法分解为三种相互依赖的方法:

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    

  def assign_adjacent_board_coords(x, y) 
    jump_positions = Hash[QUADRANTS.zip(deltas_to_board_locations(normal_deltas, x, y).each_slice(2))]    
  end

  def determine_adjacent_positions_content(board, board_coords)
    adjacent_content = {}
    board_coords.each_pair { |quad, coords| adjacent_content[quad] = board[coords[0]][coords[1]] }
    adjacent_content
  end  

非常好。