joi, 25 noiembrie 2010

Ruby for Newbies: Conditional Statements and Loops

Ruby is a one of the most popular languages used on the web. We’ve started a new screencast series here on Nettuts+ that will introduce you to Ruby, as well as the great frameworks and tools that go along with Ruby development. In this chapter, we’ll be looking at how conditional statements and loops work in Ruby.

The if statement is one of the first types of branching you learn when programming. You can guess what it means: if this is true, do one thing; if it’s not, do something else. In Ruby, these are pretty easy to write:

name = "Andrew"if name == "Andrew"puts "Hello Andrew"endif name == "Andrew"puts "Hello Andrew"elseputs "Hello someone else"end

After the keyword if, code in your conditional statement. After that comes the code to execute if the condition returns true. You close the statement with the end keyword. If you’d like, you can squeeze an else statement in there, which will predictably execute if the condition is false.

It’s not hard to check for multiple conditions. Just put as many elsif statements as you’d like between the if and else statements. Yes, that’s elsif, a marriage of else and if.

order = { :size => "medium" }def make_medium_cofeeputs "making medium statement"end#assume other functionsif order[:size] == "small"make_small_coffee;elsif order[:size] == "medium"make_medium_coffee;elsif order[:size] == "large"make_large_coffee;else make_coffee;end

As I mentioned, you can have as many elsif conditions and their corresponding code blocks as you want.

Most programming languages make a distinction between statements and expressions. A statements is a code construct that doens’t evaluate to a certain value. An expression is a code construct does return a value. For example, calling a function is an expression, because it returns a value. However, an if statement is exactly that, a statement, because it does not return a value. This means that you can’t do this in your JavaScript:

message = if (someTruthyValue) {"this is true";} else {"this is false";}

Obviously, you can’t do this because the if statement does not return a value that you can assign to message.

However, you can do this with Ruby, because statements are actually expressions, meaning they return a value. So we can do this

message = if order[:size] == "small" "making a small" elsif order[:size] == "medium" "making a medium" else "making coffee" end

Whichever block of code is executed will become the value of message.

If you don’t have any elsif or else clauses, and your if statement has only one line, you can use it as a modifier to a “normal” line.

puts "making coffee" if customer.would_like_coffee?

In most programming languages, we want to reverse the return of the conditional expression, we have to negate it, usually with the bang (!) operator.

engine_on = trueif !engine_on # meaning "if not engine_on"puts "servicing engine" #should not be put, because "not engine_on" is falseend

However, Ruby has a really nice unless operator, that keeps us from having to do that, while giving us much more readable code:

unless engine_on # "unless engine_on" is better than "if not engine_on""servicing engine"end

Just like if, you can use unless as a modifier:

puts "servicing engine" unless engine_on

If you’ve got a lot of options to work through, using if/elsif/else might be somewhat wordy. Try the case statement.

hour = 15casewhen hour < 12puts "Good Morning"when hour > 12 && hour < 17puts "Good Afternoon"elseputs "Good Evening"end

It’s kinda-sorta-maybe like a switch/case statement in JavaScript (or other languages), except that there’s no one variable you’re evaluating. Inside the case/end keywords, you can put as many when statements as you’d like. Follow that when by the conditional expression, and then the lines of code go after it. Just like the if statement, the case statement is really an expression, so you can assign it to an expression and capture a returned value.

hour = 15message = case when hour < 12 "Good Morning" when hour > 12 && hour < 17 "Good Afternoon" else "Good Evening" endputs message

If you’re familiar with JavaScript, you’ll know that the blocks of code in an if statement are surrounded by curly braces. We don’t do this in Ruby, so it may seem like Ruby is dependant on the whitespace. Nothing could be further from the truth (take that, pythonistas :) ).

If we want write your statements as one-liners, have to separate the different parts of the statements … but how? Well, you can use semi-colons:

if name == "Andrew"; some_code;else; some_code; end

If you don’t like the look of that (which I don’t), you can put the keyword then between the conditional expressions and the line of code.

if name == "Andrew" then sode_code; end

This also works for a case statement.

case when x > 20; puts "<20" when x < 20 then puts "<20"end

So, those are conditional statements (I mean, expressions). How about loops? Let’s look at while loops first.

A while loop will continue to execute until the condition stated is false:

arr = ["John", "George", "Paul", "Ringo"]i = 0while arr[i] puts arr[i] i += 1end

Here we’re looping over an array; when arr[i] returns false (meaning there are no items left in the array), the loop will stop executing. Inside the loop, we print out the current item in the array, and them add one to our increment variable.

You can also use while as a modifier

arr = ["John", "George", "Paul", "Ringo"]i = -1puts arr[i += 1] while arr[i]

Just like unless is the opposite of if, until is the opposite of while. It will continue to loop until the condition is true:

days_left = 7;until days_left == 0 puts "there are still #{days_left} in the week" days_left -= 1end

And of course, it’s a modifier, too.

days_left = 8puts "there are still #{days_left -= 1} in the week" until days_left == 1

Yes, Ruby has a for loop. No, it’s not like the for loop in other languages. It acts like a foreach loop, for looping over the values in an array or hash:

arr = ["John", "George", "Paul", "Ringo"]for item in arr puts itemend

If you’re looping over a hash, you can use two variable names, one for the key and one for the value:

joe = { :name => "Joe", :age => 30, :job => "plumber" }for key, val in joe puts "#{key} is #{val}"end

I hope you’re enjoying our Ruby for Newbies Screencast series. If there’s something you’d like to see, let me know in the comments! (And if you’re not watching the videos, you should be. There’s a screencast-only bonus at the end of each one.)


View the original article here

Niciun comentariu:

Trimiteți un comentariu