Chapter 5 Methods

Learn to Program, Third Edition — by Chris Pine (30 / 116)

The Pragmatic Programmers
The Pragmatic Programmers

--

👈 Progress Checkpoint | TOC | Fancy String Methods 👉

So far, you’ve seen a number of different methods — puts, gets, and so on. (Pop quiz: List all of the methods you’ve seen so far. There are ten of them. The answer is coming in a moment.) But we haven’t actually talked about what methods are and how they work. In this chapter we’ll do exactly that. You’ll also learn some new methods, so you can do more in your programs.

The “technical” definition of methods is that they are things that do stuff. If objects — such as strings, integers, and floats — are the nouns in the Ruby language, then methods are the verbs; and you can’t have a verb without a noun to do the verb. For example, ticking isn’t something that happens on its own; a clock has to do it. In the English language, you’d say, “The clock ticks.” In Ruby, you’d say clock.tick (assuming that clock was a Ruby object, of course, and one that could tick). Programmers might say that they were “calling clock’s tick method” or that they “called tick on clock.”

So, did you take the pop quiz? Good. Well, I’m sure you remembered the methods puts, gets, and chomp, since we recently covered those. You probably also got the conversion methods, to_i, to_f, and to_s. But did you get the other four? Yeah? No? Why, it’s none other than our old arithmetic buddies: +, -, *, and /. (Arithmetic buddies? Seriously, Chris? I don’t know why my editor even allows stuff…

--

--

The Pragmatic Programmers
The Pragmatic Programmers

We create timely, practical books and learning resources on classic and cutting-edge topics to help you practice your craft and accelerate your career.