Spandan
Spandan

Reputation: 199

Ruby - How to Execute something and then Break inside IF block?

EDIT: Someone pointed out that I needed to break correctly so I am editing the question

Scenario:
Please see following code:

print "UserID: "
uid = $stdin.gets.chomp
print "Password: "
pwd = $stdin.gets.chomp
usr_inp =  "#{uid};#{pwd}"
login_status = -1
# login_info.txt - "#{userid};#{password}" - format
File.open(File.join(File.dirname(__FILE__), 'login_info.txt'), "r") do |f|
    f.each_line do |line|
        puts line
        if (line.chomp == usr_inp)
            login_status = 1
        elsif (line.chomp != usr_inp && line.include?(uid)) #case a person inputs invalid password
            login_status = 0
        elsif (line.chomp != usr_inp && !(line.include?(uid))) #case a person inputs an invalid id
            login_status = 2
        end
    end
end
if (login_status == 1)
    puts "\nLogged in successfully: #{uid}"
elsif (login_status == 2)
    puts "\nSorry, that Employee does not exist."
elsif (login_status == 0)
    puts "\nLogin failed.\nPlease check credentials."
end

Problem:
break if (condition) exists in Ruby. But I don't waht that.
I want to do something like:

if (condition x)
    (do something)
    break
elsif (condition y)
    (do something else)
    break
else
    (whatever)
end

Maybe I am not understanding how ruby code works. Whenever I try to put the break as I want to use it, it associates with the next elsif.
Please help.

Upvotes: 2

Views: 2128

Answers (1)

knut
knut

Reputation: 27845

It depends on what you need and where you need it.

A script like this:

condition = 1
case condition
  when 1
    puts 'one'
    break
  when 2
    puts 'two'
  else
    puts 'Other %s' % condition
  end

puts 'end'

has a syntax error. break leaves a loop and there is no loop.

But with a loop, this works:

[1,2,3].each{|condition|
  case condition
    when 1
      puts 'one'
      break
    when 2
      puts 'two'
    else
      puts 'Other %s' % condition
    end
    puts 'end'
  }
  puts 'very end'

The output is:

one
very end

You see, the loop is stopped.

If you want to continue the loop with the next element, you need next (sorry, I'm just not aware what break is doing really in Java - it's been a long time since my last Java program):

[1,2,3].each{|condition|
  case condition
    when 1
      puts 'one'
      next
    when 2
      puts 'two'
    else
      puts 'Other %s' % condition
    end
    puts 'end %s' % condition
  }
  puts 'very end'

The result:

one
two
end 2
Other 3
end 3
very end

When you are not inside a loop (like in your code snippet), you may use exit (leave the program) or return (leave a method).

Upvotes: 2

Related Questions