在Ruby中设置布尔变量

3

这可能是一个愚蠢的问题,但我就是无法让它工作。我很确定我错过了什么。

我想将一个布尔值设置为 false 然后只有在满足条件时才将其设置为 true

boolTest = false

until boolTest = true
    puts "Enter one fo these choices: add / update / display / delete?"
    choice = gets.chomp.downcase

    if choice == "add" || choice == "update" || choice == "display" || choice == "delete"
        boolTest = true
    end
end

我刚开始学习Ruby,可能会混淆其他语言的能力。


boolTest = true - Sergio Tulentsev
1
另外,根据 Ruby 的约定,应该是 bool_test(蛇形命名法),而不是 boolTest(驼峰命名法)。 - Sergio Tulentsev
抱歉,我复制了错误的代码,原始代码中没有引号。 - Justin
1
这是另一个错误。直到boolTest == true - Sergio Tulentsev
2个回答

8

由于您使用了until,这实际上是在写出while not boolTest。您不能使用=,因为它是保留给赋值的;相反,省略布尔条件。
检查布尔值与布尔值之间没有价值;如果您真的想保留它,您必须使用==

boolTest = false

until boolTest
  puts "Enter one fo these choices: add / update / display / delete?"
  choice = gets.chomp.downcase

  if choice == "add" || choice == "update" || choice == "display" || choice == "delete"
    boolTest = true
  end
end

作为一条优化/可读性建议,您还可以调整布尔条件,以便在choice中没有重复的语句;您可以将所有字符串声明在一个数组中,并通过include?检查choice是否存在于数组中。
boolTest = false

until boolTest
  puts "Enter one fo these choices: add / update / display / delete?"
  choice = gets.chomp.downcase

  boolTest = %w(add update display delete).include? choice
end

你的回答现在已经无效了 :) - Sergio Tulentsev
啊,所以我不能写成 until boolTest = True - 因为现在它似乎可以工作。 - Justin
1
@cocojay,= 是一个赋值符号,你需要使用 == - Stefan

1
我认为你错过了的只是在if条件中使用"=="而不是单个"=",直到boolTest = true,这样就可以解决问题了。请注意保留html标签。
boolTest = false

until boolTest == true
  puts "Enter one fo these choices: add / update / display / delete?"
  choice = gets.chomp.downcase

  if choice == "add" || choice == "update" || choice == "display" || choice == "delete"
    boolTest = true
  end
end

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接