Class: FEEN::Parser::Square

Inherits:
Object
  • Object
show all
Defined in:
lib/feen/parser/square.rb

Overview

The square class.

Examples:

Parse a Shogi problem board and return an array

Board.new("3,s,k,s,3/9/4,+P,4/9/7,+B,1/9/9/9/9").to_a
# => [
#      nil, nil, nil, "s", "k", "s", nil, nil, nil,
#      nil, nil, nil, nil, nil, nil, nil, nil, nil,
#      nil, nil, nil, nil, "+P", nil, nil, nil, nil,
#      nil, nil, nil, nil, nil, nil, nil, nil, nil,
#      nil, nil, nil, nil, nil, nil, nil, "+B", nil,
#      nil, nil, nil, nil, nil, nil, nil, nil, nil,
#      nil, nil, nil, nil, nil, nil, nil, nil, nil,
#      nil, nil, nil, nil, nil, nil, nil, nil, nil,
#      nil, nil, nil, nil, nil, nil, nil, nil, nil
#    ]

Parse a Shogi problem board and return a hash

Board.new("3,s,k,s,3/9/4,+P,4/9/7,+B,1/9/9/9/9").to_h
# => {
#       3 => "s",
#       4 => "k",
#       5 => "s",
#      22 => "+P",
#      43 => "+B"
#    }

Instance Method Summary collapse

Constructor Details

#initialize(board) ⇒ Square

Returns a new instance of Square.

Parameters:

  • board (String)

    The flatten board.



32
33
34
# File 'lib/feen/parser/square.rb', line 32

def initialize(board)
  @board = board
end

Instance Method Details

#to_aArray

Returns The list of squares on the board.

Returns:

  • (Array)

    The list of squares on the board.



37
38
39
40
41
# File 'lib/feen/parser/square.rb', line 37

def to_a
  @board
    .split(%r{[/,]+})
    .flat_map { |str| row(str) }
end

#to_hHash

Returns The index of each piece on the board.

Returns:

  • (Hash)

    The index of each piece on the board.



44
45
46
47
48
49
50
51
52
# File 'lib/feen/parser/square.rb', line 44

def to_h
  to_a
    .each_with_index
    .inject({}) do |h, (v, i)|
      next h if v.nil?

      h.merge(i => v)
    end
end