简体   繁体   中英

ruby array iteration, counting only occupied indices

I'm trying to count the number of occupied spaces, then return that count from #turn_count . Right now I'm returning the orig array.

I'm also counting every iteration, instead of occupied indices.

board = [" ", " x", " ", " ", "O", "O", " ", " ", "X"]


def turn_count(board)
  counter = 0
board.each do |index|

  if index = "x" || index = "o"
    counter += 1
    puts "#{counter}"
  end
end

end

turn_count(board)

You just need to return the value of counter at the end of your function and also change your = to == .

= is for assignment. == is for comparison.

def turn_count(board)
  counter = 0

  board.each do |turn|
    if turn.downcase == "x" || turn.downcase == "o"
      counter += 1
      puts "#{counter}"
    end
  end

  counter
end

I've also added the downcase method so that you're comparison is consistent. Otherwise, if you're looking for x but the array contains an X , you won't get a match.


SIDENOTE:

I changed index to turn because what you're declaring for that each loop is not actually an index. It's the array element itself.

If you wanted to use the index in the loop, you'd need to do something like:

board.each_with_index do |turn, index|

SIDENOTE #2:

You could also do the each loop as a super clean one-liner:

board.each { |t| counter +=1 if ['x', 'o'].include?(t.downcase) }

Just another option. :-)

I'm trying to count the number of occupied spaces

board = [" ", " x", " ", " ", "O", "O", " ", " ", "X"]
board.count { |s| s != " " } #=> 4
[" ", " x", "    ", " ", "O", "1O", "    ", " ", "X"].count { |s| s =~ /\S/ }
  #=> 4

You can do conditional counting for an array by passing a block to count that returns true for the elements you want to count.

In the above example the element is tested against a regex looking for anything other than whitespace in the field

If i understand your question correctly, i guess you want to return the count of occupied values. To do this in ruby helpers are available. Like in your condition:

array = [" ", " x", " ", " ", "O", "O", " ", " ", "X"]

array.reject(&:blank?).count It will return a count 4 .

So here, reject will skip all the blank spaces and give a count of those elements are present.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM