简体   繁体   中英

Set boolean variable in Ruby

This might be a silly question, but I just can't get it to work. Pretty sure I've missed something.

I want to set a boolean to false Then set it to true only when a condition is met.

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

Only just starting to learn Ruby, so maybe I'm confusing the capabilities of other languages.

Since you're using until , that's effectively writing out while not boolTest . You can't use = , since that's reserved for assignment; instead, omit the boolean conditional. There's no value in checking a boolean against a boolean; if you really wanted to keep it though, you'd have to use == .

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

As an optimization/readability tip, you can also adjust your boolean conditional so that there's no repeated statement with choice ; you can declare all of thoe strings in an array, and check to see if choice exists in the array through include? .

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

I think what you missed is just "==" in the if condition until boolTest = true you should use a double = not a single one

this will work for you

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

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