Home > database >  Switch case in Ruby , making else to return data in a Break event
Switch case in Ruby , making else to return data in a Break event

Time:07-16

I currently learning ruby. I tried a small piece of code which will return the country based on the city

Code:

message = nil
flag = true
while true
    print "Enter city name : "

    city_name = gets.chomp
    message = case city_name

        when "Frankfurt" then "It is in germany"
            
        when "Paris" then "It is in France"
            
        else "Not present in memeory!!!"
            break

        end

    puts "Message is : #{message}"
end

puts "Out of the loop"

How ever when I type any other value other than frankfurt and paris, I only get "out of loop" printed and not "Not present in memory"

Based on my understanding the string given after 'then' command is being returned to the variable 'message'. Why is that the string given after else is not being returned to the variable ? When I try it without the break statement it seems to work fine.

CodePudding user response:

The docs for break explain that it's used to "leave a block early" and in particular to "terminate from a while loop".

In your code, that block is

while true
  # ...
end

When calling break, the block is left right-away and execution continues after end.

As you already figured out, the fix is to remove break if you don't want to break out of the loop. Also, if there is no condition, you can use loop instead of while true.

You might want to designate another value to break the loop explicitly, e.g. by checking for empty? string:

loop do
  print "Enter city name: "

  city_name = gets.chomp
  break if city_name.empty?

  message = case city_name
            when "Frankfurt"
              "It is in Germany"
            when "Paris"
              "It is in France"
            else
              "Not present in memory!!!"
            end

  puts "Message is: #{message}"
end

puts "Out of the loop"

Example:

Enter city name: Frankfurt
Message is: It is in Germany
Enter city name: Paris
Message is: It is in France
Enter city name: London
Message is: Not present in memory!!!
Enter city name: 
Out of the loop
  •  Tags:  
  • ruby
  • Related