Nitesh Mishra
Nitesh Mishra

Reputation: 570

Saving the state of program when condition fails in ruby

I have a nested hash and I extracted the keys from it. This key is displayed to user to select for the input now user enter the input and according to that input, it finds that key from the hash and check that key exist in hash or not if it exist in hash than program continues otherwise it gives the message invalid option and than it again display the previous message for selecting the input.

Hash :

@metals = { 
"1" => {Aluminium:  100}, 
"2" => {Steel: 80}, 
"3" => {Copper: 60}
}

My code :

def getmetal
    puts "Which metal do you want to use?"
    @metals.each do |key1, value1|
       value1.each do |key2, value2|
        puts "Enter #{key1} for #{key2}"
      end
    end
    @metalsdata = gets.chomp
    if @metals.has_key?(@metalsdata)
        @metalname, @metalprice = @metals[@metalsdata].first
    else
        puts "Invalid option"
    end 
end

I have done this much part now i want to do is if user has entered wrong option than an error message is displayed that "please select the valid input" and than after that it again ask for the input. Suggest me how i will implement that?

Upvotes: 0

Views: 47

Answers (1)

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 121010

while [email protected]_key?(@metalsdata = gets.chomp) do
  puts 'Please enter correct value'
end
@metalname, @metalprice = @metals[@metalsdata].first

Upvotes: 1

Related Questions