
Saved by Harold T. Harper
Learn to Program
Saved by Harold T. Harper
caps_array = [] # array literal, same as Array.new - caps_hash = {} # hash literal, same as Hash.new
You might be thinking to yourself, “This is a lot like the loops from earlier.” Yep, it’s similar. One important difference is that the method each is simply that: a method. while and end (much like do, if, else, and all the other keywords) are not methods. They are a fundamental part of the Ruby language, like = and parentheses; they are kind of l
... See moreLet’s start with a short example: 1: toast = Proc.new do 2: puts "Cheers!" 3: end 4: 5: toast.call 6: toast.call 7: toast.call <= Cheers! Cheers! Cheers!
Well, here’s the big secret behind the puts method: before puts tries to write out an object, it uses to_s to get the string version of that object. In fact, the s in puts stands for string; puts actually means put string.
So, you def(ined) the method say_moo. (Method names, like variable names, almost always start with a lowercase letter.
With blocks and procs, you have the ability to take a block of code (code in between do and end), wrap it up in an object (known as a proc), store it in a variable or pass it to a method, and run the code in the block whenever you feel like it (more than once, if you want). So, it’s kind of like a method itself, except it isn’t bound to an object (
... See moreThe variable number_of_moos points to the argument passed in. I’ll say that again, because it’s a little confusing: number_of_moos is a variable that points to the argument passed in. So, if you type say_moo(3), the variable number_of_moos points to the value 3 when the method is being run.
Sometimes these special variables that methods have, like number_of_moos, are called parameters: parameters are the variables that point to arguments. But they aren’t the only kind of variables your methods can have. To help you write clean, encapsulated code, you can also create local variables.
But this isn’t true with each; each is simply another method. (In this case, it’s a method that all arrays have. We’ll see more array methods in the next section.) Methods like each that “act like” loops are often called iterators because they iterate over each element in some collection.