在Ruby中计算字符串中的X和O

在Ruby中计算字符串中的X和O,ruby,Ruby,我不确定为什么我的代码不工作,我认为我的逻辑是正确的 让函数ExOhstr接受正在传递的str参数,如果x和o的数目相等,则返回字符串true,否则返回字符串false。字符串中只输入这两个字母,没有标点符号或数字。例如:如果str是xooxxxooxo,那么输出应该返回false,因为有6个x和5个o ExOh(str) i = 0 length = str.length count_x = 0 count_o = 0 while i < length if str[i]

我不确定为什么我的代码不工作,我认为我的逻辑是正确的

让函数ExOhstr接受正在传递的str参数,如果x和o的数目相等,则返回字符串true,否则返回字符串false。字符串中只输入这两个字母,没有标点符号或数字。例如:如果str是xooxxxooxo,那么输出应该返回false,因为有6个x和5个o

ExOh(str) 
i = 0 
length = str.length 
count_x = 0 
count_o = 0 

while i < length 
if str[i] == "x"
    count_x += 1 
elsif str[i] == "o" 
    count_o += 1 
end 
i+=1 
end 
    if (count_o == count_x)
        true 
    elsif (count_o != count_x)
    false 
end 
end 

代码的问题是函数声明。在起动时使用def ExOhstr。如果您也缩进,可能会有所帮助

def ExOh(str)
  i = 0
  length = str.length
  count_x = 0
  count_o = 0

  while i < length
    if str[i] == "x"
        count_x += 1
    elsif str[i] == "o"
        count_o += 1
    end
    i+=1
  end

  if (count_o == count_x)
    true
  elsif (count_o != count_x)
    false
  end
end

你也打败了我。这个使用count的简单解决方案是最好的方法谢谢你,我不敢相信我忘记了前面的def,我正在绞尽脑汁为什么它不工作!
def ExOh(str)
  str.count('x') == str.count('o')
end