coursera - SaaS - 3.1 - Ruby 101

Uploaded by ardemiranda on 28.02.2012

So let's start with just, kind of, the very, very basics. What, what is this
language like? It's interpreted, it's a scripting language. So there's no compile
time. That means that there are certain compiler error messages that will not save
you from silly mistakes. But we're gonna talk about techniques that will help you
avoid them anyway. It's object oriented, and I know Java is also object oriented,
but this is different. Everything is really an object, and this is kind of the
one pillar of the language you'll, you'll absorb. Once you understand this, that
everything is an object, and [inaudible] the only way to do anything is to send
messages to objects that call methods. It'll save you a lot of. Grief and trying
to sort of decipher what might look like a, unfamiliar code. It is dynamically
typed. What does that mean? Beside the fact that it means you can't tell the type
of things with certainty until run time. It means that although, objects to have
types, the variables that refer to them don't have types. So, if you're coming
from Java, this is gonna seem weird. If you're coming from Python you've probably
already seen this. We'll do examples of all of this stuff. And probably, most
importantly for our purposes, it's highly dynamic. There's a lot of things you can
do at run time that in other languages you could only do at compile time. In fact,
it's not too much of an exaggeration to say that in Ruby, there's no other time
but run time. Even things that look like class declarations are not really
declarations. They're code that gets executed to create new things that run
time. So again we'll see examples but the fact that Ruby has this feature means that
it's become pervasively used to make your code more concise and more elegant and
we'll do some hopefully informative examples of this today. Okay, so let's
just do some basics, some naming conventions. Every language has
conventions. If you?re not familiar with the terms camel case and snake case, camel
case has humps in it. So let's get the mouse over here, there we go. Upper camel
case is when the first letter is uppercase; snake case has little snakes,
underscores between the words. These are real terms, folks. I'm not making'em up.
So conventionally, when you define a class, you use camel case, method names,
and variable names, typically use snake case. Notice that method names can
optionally end in an interrogation mark, question mark. If it's con, by convention,
if a method returns a bullion or as a predicate, you end up with a question
mark. You can optionally end it with a bang, if it's a dangerous method, right? A
method that does something destructive or that can't be undone. But those are
conventions, you don't have to do that. Constants are in all capital letters, and
they're scoped. That means that, like all other variables, they're visible only
within the scope in which they're defined. There's also globals. They're in red
because red is dangerous. Don't use globals, they're bad for you. But if you
really need to use them they begin with a dollar sign. They're usually all
uppercase, and they really are truly global. You can see and modify them from
absolutely everywhere. Big red flag. Symbols. Those of you who took CS61A
classic, where you did Scheme, have seen the concept of a symbol before. But if you
aren't familiar with the Scheme language, this may be new to you. A symbol is really
just an immutable string. A string whose value can't change And its value is
itself, that's all it is. They begin with a colon. They don't have to be lower case,
but most commonly, they are. >> It's not the same as a string in that you can
convert back and forth you can go from a symbol to a string and you can go back but
they're not equal to each other. Now why would you've two kinds of things, one
argument is well you know, if you can have lot of strings that have the same value
you could save some memory but you know, saving a byte here and there is ridiculous
right. The real reason that symbol use in [inaudible] that they cannot specialness,
so when you see a method that takes a symbol as one of its arguments, typical
what it?s trying to tell you is. This looks like a string but it's not an
arbitrary string, it's one of a fixed set of possible values, right? Now again, as
we'll see, idiomatically some methods are written such that you can either pass a
string or a symbol, whichever is more convenient for you. But, in terms of using
the language that way that Rubyists use it a symbol usually means, I'm not just a, a
string, I am one of a fixed set of special strings and it's not like I could have an
arbitrary value. Okay variables erase hashes. There are no declarations okay.
You have to assign a variable before you use it otherwise you'll get an error but
if you, when we talk about OOP in a moment the instance in class variables of a
class, those actually get to follow values of nil until they are signs. Its okay to
if reference to those. So it might seem strange, unless you've come from a
language like Python, to see something like X=3. And then a few lines later, X= a
string. But that's perfectly fine. Because, again, objects like three and
[inaudible] have types. But the variables that refer to them have, don't have types,
right? The only thing that has a type B reference is when you try to use the
variable, the thing that it references. That's the type that matters. You'll never
see something like this, because there are no declarations. Arrays. Standard linear
arrays like in every other language but again what might seem new to you is arrays
don't have to have elements that are all of the same type. So you don't talk about
an array of [inaudible] or an array of strings; it's just plain old 'an array'.
Right? You can reference elements of the array with the numeric index. That should
look familiar. You can ask it what its length is. This should all be familiar
[inaudible] languages. And similarly hashes. There are a few different
notations but this is probably the most commonly used one involving braces. Just
like an array the keys and values of hashes don't all have to be of the same
type. In practice they often are but you know so that I'm telling you the rules
honestly. Here is a hash. Whose first key, well I shouldn't say first key, hashes
aren't ordered, but that has a key which is the string A with a corresponding value
one, the symbol B, which is not the same as the string B, and the value of that key
is an array. So in fact, the array and hash elements can be anything at all
including other arrays or other hashes. They don't all have to be of the same
type. And, if you use Python and Pearl hashes, you kind of think of them as the
Swiss army chainsaw for building up data structures, not too different in Ruby.
Okay. We're almost through with nuts and bolts stuff. Methods. Everything is
basically passed by reference, so here's a very simple method definition. Phu Of X
and Y. [inaudible] Whoops, sorry about that. That just returns an array of X and
Y+1. How could you call this method? Well down here you could call it with A comma B
equals phu of X and Y. Right you can assign to individual elements as well as
an array. I could also, in my definition of the method, supply a default value for
some of the arguments and that means that if those arguments aren't present in the
call, they'll be the default value. So, if I just call this [inaudible] of x, as long
as I gave a default value for y, that's a legal call. For obvious reasons, you
couldn't for example, specify a default value for x, but then make y a required
parameter because there would be no good way to parse that. Alright, so, that's
also legal. And, lastly, although typically statements are separated by new
lines, they can be separated by semi-colons. It's less, less usual, but
sometimes if statements are really short and like an entire method will fit on a
line you'll sometimes see that. Okay, and last but not least I think, some basic
constructs. Statements end with semicolons or newlines, but if the parsing is
unambiguous they can actually span a line. So what does that mean? Looking at the
statement on the left. A raise is a way to raise an exception. This is all in the
book by the way. So raise this exception unless the ship is stable. Breaking a line
after a less is legal because in terms of arcing a less can't be the last thing in a
statement. It's gotta be followed by some condition. But, on the other hand. On the
right hand side, breaking the line after raise boon is gonna be a problem, because
raise boon all by itself a legal statement. So the partial will actually
stop there and then the partial will complain that you have got and lost
without a corresponding thing to do. Okay. So again when in doubt, do the defensive
thing but because you are gonna be looking at a lot of Ruby code, I wanted to show
you some examples of different ways of you see things done. Hmm, all of the basic
comparison that you would expect including equal [inaudible] and bank [inaudible]
which are for regular expressions which we'll look at in a moment. Boolean values,
True, False and No are constants. False and No are the things that, in a
conditional statement evaluate to False. Everything else in a conditional statement
evaluates to True. So beware if you're used to Python or Pearl where things like
the empty array or the empty string will evaluate to false, not so in Ruby, okay?
If it's False or Nil, that's False, everything else, absolutely everything
else is True. And again, as in most other languages, the usual control flow, you've
got If with Else, you've got While statements, you've got various kinds of
loops. But I don't really want you to think too much about the loops because,
during the lecture today, we're going to see that in fact loops are just a special
case of a different kind of Ruby construct called an iterator, which is pervasive.
Okay strings in regular expressions. Just last week I discovered a great new set
called Regular. Try it for all your regular expression needs. If you had used
Regaxis in other languages ruby is a pretty compable. Ha, ha. Get that? Never
mind. [laugh] Thank you. Wake up. [laugh] Strings and regular expressions. Various
ways to express a string. Basically if a string has double quotes around it you can
embed expressions into it with this pound brace notation. Strings with single quotes
have nothing done to them. So, and why, what is this percent capital Q and percent
lowercase q? These are just ways to represent strings that have special
characters in them. So, one way to, to have a string with double quotes in it, is
to use percent cap Q or percent lowercase Q to quote it. How do you match springs
against a regular expression? 1-Syntax is the one that Ruby has borrowed from Perl,
Python and other languages. I can take a string, and use the equal twittle operator
to compare it to a regular expression. Since you've all been keeping up with the
reading, you know that this regular expression is gonna match an email
address, with the first part being the part before the at sign and the part after
the at sign, and that it's going to capture both of these groups. We'll talk
about accessing the capture in just a moment. Interestingly, you can also
reverse the sense of the comparison, and in a moment we'll talk about why this
works. But I could also take a regular expression and equal twiddle compare it
against a string. In either case, If the match fails. Then the value of the
expression as a whole is false. If the match succeeds, you get a none false
value. Depending on which form you use. You get different none false values but,
you'll be able to capture. All of the expression groups with dollar one through
dollar however many [inaudible] there were. So in this example when I'm matching
this [inaudible] against fox [inaudible] edu. This first group of [inaudible] is
capturing everything before the app. So dollar one will be the string fox that
match that. And the second group of parens will be captured by dollar two, that's
everything after the at-sign which is actually Berkeley dot, yeah just Berkeley
because the dot edu anchored to the end of the string is outside the match. One of
the things that I've always kind of hated about programming classes is we expect you
to write code in a new language without letting you read code in that language.
You would never take a writing class in Literature and have them say, write a
great essay, but don't ever have read, you know, the great essays of other authors.
So, once in a while, I'm gonna show you an example of code that I don't necessarily
expect you to fully understand, but it's because I want to acclimatize you to what
some of these things look like in real life. So, with that in mind, let?s take a
look at. An example of a real use of a regular expression this way. Click. Good.
I was hoping that would work. Okay. By the way I love pastin'. Okay, so here is an
example of real life use of a Regex, let me see if I can make that a little bit
bigger. This is actually a snippet of code from the auto grader that's going to be
used to grade your all's homework, in case you're interested. So what's going on here
is we actually run our spec which is a testing tool in a controlled environment,
and from its output, we look for a message that says how many examples, how many test
cases were run, how many failures there were, and optionally how many were
pending. And if the match succeeds then we will quote how many total failed and
passing examples we had and if the match fails, then we throw up our hands in
despair and hopefully that doesn't happen too often. But again, the goal of this is
not to have [inaudible] the entire piece of codes that's on the screen, it's to
give you a sense of, of what code looks like. So, as you see more examples you
will become more comfortable with that. All right. So I think with that in mind we
can do our first mental calisthenics.