How to break out of a case...while in Ruby
What's wrong with:
case x
when y;
<code here>
if !something
<more code>
end
end
Note that if !something
is the same as unless something
How to break out of case statement in Ruby
If that is all you have in the method body, then just do return
instead of break
.
If you cannot do that, then do:
when 1
unless <already executed for some similar data>
#Some code
end
when 2
...
How to break out from a ruby block?
Use the keyword next
. If you do not want to continue to the next item, use break
.
When next
is used within a block, it causes the block to exit immediately, returning control to the iterator method, which may then begin a new iteration by invoking the block again:
f.each do |line| # Iterate over the lines in file f
next if line[0,1] == "#" # If this line is a comment, go to the next
puts eval(line)
end
When used in a block, break
transfers control out of the block, out of the iterator that invoked the block, and to the first expression following the invocation of the iterator:f.each do |line| # Iterate over the lines in file f
break if line == "quit\n" # If this break statement is executed...
puts eval(line)
end
puts "Good bye" # ...then control is transferred here
And finally, the usage of return
in a block:return
always causes the enclosing method to return, regardless of how deeply nested within blocks it is (except in the case of lambdas):
def find(array, target)
array.each_with_index do |element,index|
return index if (element == target) # return from find
end
nil # If we didn't find the element, return nil
end
Looping through a case statement in Ruby?
I'd write it like:
loop do
input = gets.chomp.downcase
case input
when 'help'
puts "Available commands are..."
# more when statements go here...
when 'exit'
break
else
puts "That is not a valid command. Type 'HELP' for available commands."
end
end
puts "Goodbye!"
A loop
is designed for this sort of case, where you just want to loop cleanly, and then eventually break out on some condition.For ultimate clarity in what the code is doing, I'd put the exit
immediately after reading the input, instead of being embedded in the case
statements. It's a minor thing, but is useful to remember if you're coding and others have to help maintain it:
loop do
input = gets.chomp.downcase
break if input == 'exit'
case input
when 'help'
puts "Available commands are..."
# more when statements go here...
else
puts "That is not a valid command. Type 'HELP' for available commands."
end
end
puts "Goodbye!"
Ruby remove the implicit break in Case statement? (How to make case like Switch)
Michael,
While your example is a bit misleading ('bob' matches both 'bob' and "bob" so the first case would always match), you just can use simple if's like in if_test
method below :
def case_test(x)
puts case
when x > 3
"ct: #{x} is over 3"
when x > 4
"ct: #{x} is over 4"
end
end
case_test(4)
case_test(5)
def if_test(x)
puts "it: #{x} is over 3" if x > 3
puts "it: #{x} is over 4" if x > 4
end
if_test(4)
if_test(5)
This yields :ct: 4 is over 3
ct: 5 is over 3
it: 4 is over 3
it: 5 is over 3
it: 5 is over 4
Note that you can also use multiple statements with when
, which might help you or not depending on your real use case :def many(x)
case x
when 'alice','bob'
puts "I know #{x}"
else·
puts "I don't know #{x}"
end
end
many('alice')
many('bob')
many('eve')
Yields :I know alice
I know bob
I don't know eve
How to write a switch statement in Ruby
Ruby uses the case
expression instead.
case x
when 1..5
"It's between 1 and 5"
when 6
"It's 6"
when "foo", "bar"
"It's either foo or bar"
when String
"You passed a string"
else
"You gave me #{x} -- I have no idea what to do with that."
end
Ruby compares the object in the when
clause with the object in the case
clause using the ===
operator. For example, 1..5 === x
, and not x === 1..5
. This allows for sophisticated when
clauses as seen above. Ranges, classes and all sorts of things can be tested for rather than just equality.
Unlike switch
statements in many other languages, Ruby’s case
does not have fall-through, so there is no need to end each when
with a break
. You can also specify multiple matches in a single when
clause like when "foo", "bar"
.
Ruby stop iterate in case block if return true
In case resource
ruby compares your resource with every expression using ===
. It seems, that match...
methods returns booleans, so that you will always get a default value.
To make this work you could get rid of resource. With empty case you will get an expected behaviour.
def score(resource)
case
when match_invoice_number(resource) then 0
when match_amount(resource) && match_vendor(resource) then 1
when match_vendor(resource) then 3
else -1
end
end
However, it is not a good practice to use empty cases. If-else is the tool that solves this task better.def score(resource)
if match_invoice_number(resource)
3
elsif match_amount(resource) && match_vendor(resource)
2
elsif match_vendor(resource)
1
else
0
end
end
Switch case in Ruby , making else to return data in a Break event
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
break and return in ruby, how do you use them?
Return exits from the entire function.
Break exits from the innermost loop.
Thus, in a function like so:
def testing(target, method)
(0..100).each do |x|
(0..100).each do |y|
puts x*y
if x*y == target
break if method == "break"
return if method == "return"
end
end
end
end
To see the difference, try:testing(50, "break")
testing(50, "return")
Related Topics
Private Messages with Faye and Rails
Alias_Method on Activerecord::Base Results in Nameerror
How to Send an Image on The Web in an Xmpp (Jabber) Message
Sinatra Not Persisting Session with Redirect on Chrome
Where to Reopen a Class in Ror
Clean Install Osx 10.9.1 Returns "Undefined Method 'Path2Class'" When Trying to Install Gems
Can't Log into Active Admin. Any Way to Create an Admin User
How to Send a Keep-Alive Packet Through Websocket in Ruby on Rails
How to Programmatically Remove "Singleton Information" on an Instance to Make It Marshal
Actionmailer Pass Local Variables to The Erb Template
Activemodel::Validations on Anonymous Class
How to Access a Toplevel Entity in Ruby, from Inside a Module Which Defines The Same Name
Ruby Readline Fails If Process Started with Arguments
Recommended Way to Generate a Presigned Url to S3 Bucket in Ruby
Is There a Command Line Framework for Ruby
How to Access Sinatra App on Host Machine with Vagrant Forwarded Ports