rubyarrayshashiterationparallel-assignment

Ruby: Hash assignment with concurrent loops


Say I have an array:

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

and I have another array of strings:

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

and I have a 8 x 8 2-d array consisting of board locations(@board) that are either nil or Checker objects.

My goal is to create a hash such:

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]] }

I have the following code:

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

And then the test:

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

fails because all the assignments are of class 'Checker' and turns out they're all the same 'Checker' object. I know its doing this because the loops are nested so all the 'quad' keys are getting initialize to the last board location.

Is there a way I can assign the value to the key with a value from the 'array' in one pass so that they get assigned correctly? Does this question even make sense?


Solution

  • I think you just need to add a little map to my answer to your other similar question:

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

    Given a board like this:

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

    the above construct gives me a hash like this:

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

    and that seems to be what you're looking for.