Set boolean variable in Ruby

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

I want to set boolean to false

Then set the value true

only when the 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

      

I am just starting to learn Ruby, so I may be confusing the possibilities of other languages.

+3


source to share


2 answers


Since you are using until

this effectively writes while not boolTest

. You cannot use =

as it is reserved for assignment; omit the boolean conditional instead. There is no value in testing boolean against boolean; if you really wanted to keep it, you 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 hint, you can also set up a boolean conditional so that there is no repetition with choice

; you can declare all thoe strings in the array and check if exists choice

in the array via 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

      

+6


source


I think you only missed "=="

in if condition

until boolTest = true

, you must use double = not 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

      

0


source







All Articles