Monday, 7 July 2014

Ruby - Case Statements

Now we know how to get data from a user (using gets) or from the system (an Array),   we need to look at how Ruby can respond to the data depending on certain conditions. One way is using a Case statement. Sometimes these are referred to as switch statements in other languages.

The astute may be asking why we wouldn’t use If statements. They seem similar, but in my experience we should use them in very different ways. A Case statement gives us great control over the flow of a program. I’ve used it many time to select sets of Test Cases or call groups of methods or classes relevant to a particular test condition I’m running. This probably harks from my background doing batch scripts where I never had a single method or case to draw from.

If statements on the other hand always feel more complex. When I have multiple conditions to evaluate I will often nest If statements, I’d never nest a Case statement. That might be bad practice but hey, I’m a tester not a developer ;p




YouTube Channel: [WATCH, RATE, SUBSCRIBE]

First, let’s get some data from the user:

print "What's your name?"
name = gets.chomp.downcase

The Case statement will be run against the object holding the data, in this example that’s our variable called name. (Do you recall what type of variable this is?)

Here’s the outline Case statement for name:
case name
  when
   
  else

end

In the case of name, when it’s a certain name we care about do some stuff. Else if it’s not, do some other stuff. That’s essentially what this says. Let’s type the following and see what it does for us:

case name
  when "Mark"
    puts "...ah, the tester"
   
  when "Dave"
    puts "...ah, the gamer"
 
  else
    puts "I don't know you!"

end

The above should be easy to work out, but there’s a catch – it will fail. Do a static code review and see if you can find the defect? (Highlight the below for the answer!)

-----
Answer here: Name uses .downcase, so the input will be ‘mark’ or ‘dave’, not ‘Mark’ or ‘Dave’ that is being tested for.
---
When using a Case statement, always finish with the else as the last option. This is your catch all in case the user doesn't enter the options you have a response for.

For each of the when elements, you can add whatever code you want, but as always try and keep it simple. A good way is to build methods and classes to call, well look at those soon.



0 comments: