在Ruby中用字符串计算X和O.

时间:2016-08-15 02:23:08

标签: ruby

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

让函数ExOh(str)接受传递的str参数,如果有相同数量的x和o,则返回字符串true,否则返回字符串false。只会在字符串中输入这两个字母,没有标点符号或数字。例如:如果str是“xooxxxxooxo”,那么输出应该返回false,因为有6个x和5个。

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 

1 个答案:

答案 0 :(得分:2)

代码的问题是函数声明。一开始就使用def ExOh(str)。如果你缩进也可能会有所帮助。

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 https://ruby-doc.org/core-2.2.0/String.html#method-i-count

的更简单的解决方案
def ExOh(str)
  str.count('x') == str.count('o')
end