Skip to Main Content
Learn to Program, 2nd Edition
book

Learn to Program, 2nd Edition

by Chris Pine
March 2009
Intermediate to advanced content levelIntermediate to advanced
194 pages
4h
English
Pragmatic Bookshelf
Content preview from Learn to Program, 2nd Edition

The Method each

The method each allows us to do something (whatever we want) to each object the array points to. (It looks weird, though, and this can throw people off, so brace yourself.)

For example, if we want to say something nice about each language in the following array, we could do something like this:

languages = [​'English'​, ​'Norwegian'​, ​'Ruby'​]
languages.each ​do​ |lang|
puts ​'I love '​ + lang + ​'!'
puts ​'Don​\'​t you?'
end
puts ​'And let​\'​s hear it for Java!'
puts ​'<crickets chirp in the distance>'
I love English!
Don't you?
I love Norwegian!
Don't you?
I love Ruby!
Don't you?
And let's hear it for Java!
<crickets chirp in the distance>

What just happened? (Aside from Java getting pwn3d, heh-heh.) Well, we were able to go through ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Learn to Program, 3rd Edition

Learn to Program, 3rd Edition

Chris Pine
The Book of Ruby

The Book of Ruby

Huw Collingbourne

Publisher Resources

ISBN: 9781680500172Errata