我想在 Ruby 上转换几行 Python 代码,摘自 Thomas Guest 签署的这篇优秀文章:http://wordaligned.org/articles/drawing-chess-positions
(注:我是一个真正的 Python 菜鸟)
这是原始 Python 版本的副本:
def expand_blanks(fen):
'''Expand the digits in an FEN string into spaces
>>> expand_blanks("rk4q3")
'rk q '
'''
def expand(match):
return ' ' * int(match.group(0))
return re.compile(r'\d').sub(expand, fen)
def outer_join(sep, ss):
'''Like string.join, but encloses the result with outer separators.
Example:
>>> outer_join('|', ['1', '2', '3'])
'|1|2|3|'
'''
return '%s%s%s' % (sep, sep.join(ss), sep)
def ascii_draw_chess_position(fen):
'''Returns an ASCII picture of pieces on a chessboard.'''
pieces = expand_blanks(fen).replace('/', '')
divider = '+-+-+-+-+-+-+-+-+\n'
rows = ((outer_join('|', pieces[r: r + 8]) + '\n')
for r in range(0, 8 * 8, 8))
return outer_join(divider, rows)
使用示例:
>>> fen = "r2q1rk1/pp2ppbp/1np2np1/2Q3B1/3PP1b1/2N2N2/PP3PPP/3RKB1R"
>>> print ascii_draw_chess_position(fen)
+-+-+-+-+-+-+-+-+
|r| | |q| |r|k| |
+-+-+-+-+-+-+-+-+
|p|p| | |p|p|b|p|
+-+-+-+-+-+-+-+-+
| |n|p| | |n|p| |
+-+-+-+-+-+-+-+-+
| | |Q| | | |B| |
+-+-+-+-+-+-+-+-+
| | | |P|P| |b| |
+-+-+-+-+-+-+-+-+
| | |N| | |N| | |
+-+-+-+-+-+-+-+-+
|P|P| | | |P|P|P|
+-+-+-+-+-+-+-+-+
| | | |R|K|B| |R|
+-+-+-+-+-+-+-+-+
我试图做一些修改来转换 Ruby 中的每一行...我想知道这是否是一个糟糕的开始:s但我还是发布了它:
def expand_blanks(fen)
def expand(match)
return ' ' * int(match.group(0))
end
# bugged:
re.compile(r'\d').sub(expand, fen)
end
def outer_join(sep, ss)
sep + sep.join(ss) + sep
end
def ascii_draw_chess_position(fen)
pieces = expand_blanks(fen).replace('/', '')
puts pieces.class
divider = "+-+-+-+-+-+-+-+-+\n"
# bugged lines:
rows = ((outer_join('|', pieces[r, r + 8]) + '\n')
for r in range(0, 8 * 8, 8))
return outer_join(divider, rows)
end
end
fen = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR"
puts ascii_draw_chess_position(fen)
如果您看到我可以修复的一些行,我会很高兴。谢谢大家。
最佳答案
从 outer_join
开始依次查看每个方法。
在 Python 中,join
是一种字符串方法,它采用序列并连接由字符串分隔的元素。例如'|'.join(['p, 'p', 'p'])
在 Ruby 中,join
是一种数组方法,它将分隔符作为参数,例如['p', 'p', 'p'].join('|')
因此 outer_join
的 Ruby 版本将是:
def outer_join(sep, ss):
sep + ss.join(sep) + sep
end
接下来看expand_blanks
,这里的目的是将一个数字替换为同等数量的空格。在 Ruby 中,可以使用 gsub 替换字符串中所有出现的模式来实现这一点。可以使用一个 block 来调用 gsub,该 block 将传递每个匹配子字符串并返回应该替换匹配的字符串。所以 Ruby 代码是:
def expand_blanks(fen)
fen.gsub(/\d/) { |match| ' ' * match.to_i }
end
最后,在 ascii_draw_chess_position
中,我们可以再次使用 gsub
作为 Python 的 replace
方法的等价物,并使用 Ruby 的 map
函数代替了使用 Python 中的列表推导式所实现的功能,如下所示:
def ascii_draw_chess_position(fen)
pieces = expand_blanks(fen).gsub('/', '')
divider = "+-+-+-+-+-+-+-+-+\n"
rows = (0...8).map do |i|
row = pieces[i * 8...(i + 1) * 8].split('')
outer_join("|",row) + "\n"
end
puts outer_join(divider, rows)
end
如果您需要有关上述内容的更多详细信息,请告诉我。
关于python - 代码翻译,从 Python 到 Ruby,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2129227/