简体   繁体   English

红宝石数组迭代,仅计算占用的索引

[英]ruby array iteration, counting only occupied indices

I'm trying to count the number of occupied spaces, then return that count from #turn_count . 我正在尝试计算已占用空间的数量,然后从#turn_count返回该计数。 Right now I'm returning the orig array. 现在,我要返回orig数组。

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 == . 您只需要在函数末尾返回counter的值,并将=更改为==

= 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. 我还添加了downcase方法,以便您进行比较是一致的。 Otherwise, if you're looking for x but the array contains an X , you won't get a match. 否则,如果您要查找x但数组包含X ,则不会匹配。


SIDENOTE: 边注:

I changed index to turn because what you're declaring for that each loop is not actually an index. 我将index更改为turn因为您为每个循环声明的实际上不是索引。 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: 观点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. 您可以通过传递要计数的块来对数组进行条件计数,该块对要计数的元素返回true。

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 . array.reject(&:blank?).count它将返回一个计数4

So here, reject will skip all the blank spaces and give a count of those elements are present. 因此,在这里, reject将跳过所有空格,并给出存在这些元素的计数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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