Ruby Splat操作员或正则表达式不工作?
我不熟悉Ruby,并将国际象棋作为一种学习练习。我正试图重构一些代码,但我遇到了阻碍 为什么这样做有效:Ruby Splat操作员或正则表达式不工作?,ruby,regex,splat,Ruby,Regex,Splat,我不熟悉Ruby,并将国际象棋作为一种学习练习。我正试图重构一些代码,但我遇到了阻碍 为什么这样做有效: @available_moves = [] #part of castling logic @available_moves << "c1" if empty?("b1") && empty?("c1") && empty?("d1") def empty?(position) get_space(position).token =~ /_
@available_moves = []
#part of castling logic
@available_moves << "c1" if empty?("b1") && empty?("c1") && empty?("d1")
def empty?(position)
get_space(position).token =~ /_/
end
# sample tokens: "_e4", "ka2", "_b3"
@available\u moves=[]
#铸造逻辑的一部分
@可用\u moves使用all?
测试所有位置是否返回true,而不是使用每个
:
positions.all? { |position| get_space(position).token =~ /_/ }
positions.all?
仅当块为每个位置返回true时才为true 关于您需要做什么,其他答案就在这里,但您应该理解当前解决方案不起作用的原因
你走在正确的道路上,但你只需要更深入地观察你的逻辑。让我们从代码中考虑这两行:
@available_moves << "c1" if empty?("b1") && empty?("c1") && empty?("d1")
@available\u就是这个。也就是说,我不确定我是否完全理解为什么每个都不起作用。。。我想我得稍微考虑一下,每个方法的返回值就是它迭代的列表。因此,该方法调用的返回值是[“b1”、“c1”、“d1”]
,这意味着if emptyii?
将始终为true……因为非nil/非false将被评估为truthy。
@available_moves << "c1" if empty?("b1") && empty?("c1") && empty?("d1")
@available_moves << "c1" if emptyii?("b1", "c1", "d1")