Search code examples
rubyregexsplat

Splat operator or regex not working?


I'm new to Ruby and building Chess as a learning exercise. I'm attempting to refactor some code, and I'm stymied.

Why does this work:

@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"

...and this doesn't?:

@available_moves = []

@available_moves << "c1" if emptyii?("b1", "c1", "d1")

def emptyii?(*positions)
  positions.each { |position| get_space(position).token =~ /_/ }
end

It's probably something pretty stupid, but I can't figure out what I'm doing wrong.


Solution

  • Instead of using each, use all? to test that all positions return true:

    positions.all? { |position| get_space(position).token =~ /_/ }
    

    positions.all? will only be true if the block returns true for each of the positions.