ŷ

Jump to ratings and reviews
Rate this book

Metaprogramming Ruby: Program Like the Ruby Pros

Rate this book
Everyone in the Ruby world seems to be talking about metaprogramming--how you can use it to remove duplication in your code and write elegant, beautiful programs. Now you can get in on the action as well.

This book describes metaprogramming as an essential component of Ruby. Once you understand the principles of Ruby, including the object model, scopes, and eigenclasses, you're on your way to applying metaprogramming both in your daily work and in your fun, after-hours projects.

Learning metaprogramming doesn't have to be difficult or boring. By taking you on a Monday-through-Friday workweek adventure with a pair of programmers, Paolo Perrotta helps make mastering the art of metaprogramming both straightforward and entertaining.

The book is packed

296 pages, Paperback

First published January 1, 2010

53 people are currently reading
641 people want to read

About the author

Paolo Perrotta

6books11followers

Ratings & Reviews

What do you think?
Rate this book

Friends & Following

Create a free account to discover what your friends think of this book!

Community Reviews

5 stars
386 (49%)
4 stars
280 (35%)
3 stars
89 (11%)
2 stars
13 (1%)
1 star
10 (1%)
Displaying 1 - 30 of 45 reviews
Profile Image for Michael.
162 reviews73 followers
May 29, 2011
Before anything else, I have to say I really didn't like the style the author chose for the first part of the book. In the chapters named "Monday" to "Friday", you go through your first week in a new job, doing pair programming with your colleague "Bill". While this is fun for about half a page, sentences like "Bill walks over to the whiteboard and starts drawing a blablabla" get old fast. Very fast. I'm not exactly sure why the author decided on this style, since in my opinion it doesn't add anything to the text. As Greg Brown showed in "Ruby Best Practices" you can write an engaging text about advanced Ruby concepts without falling back to alibi prose. The second part of the book deals with some Rails internals and is written in a "normal" style, which I much prefer.

With that out of the way, "Metaprogramming Ruby" is a very good book. The concepts and their presentation are solid and the author knows where to draw the line and leave things for further exploration by the reader. I think there's a slight over-use of footnotes and sidebars, which can disturb the reading flow a bit, but it's not very dramatic and unfortunately this is not that uncommon in technical books.

What I like best is the author repeatedly points out that the distinction between "regular" programming and metaprogramming are blurry in Ruby at best, and that the latter in the end isn't some obscure sort of magic, but "just" a powerful set of tools that can be immensely helpful when used responsibly. Even advanced Ruby programmers are likely to pick up a new trick here or there or at least further their understanding of certain concepts.
Profile Image for Tamara.
116 reviews24 followers
March 24, 2013
's is a tour de force on Ruby's Object Model. The book goes into considerable depth on how it works, and presents many examples of manipulating the object model to good use. The format of first section of the book goes through a week of a pair of Ruby programmers as they try to fix and refactor an existing application, and how they use various metaprogramming "spells" (techniques, idioms, etc). The second section is a set of essays talking directly to the reader, rather than talking about people working on something. The third section is a set of appendecies that encapsulate the various concepts discussed in the first two sections.

One of the very nice things I liked about the first section is the use of hand-drawn images to depict the concepts being discussed. Not only does this give a sense of "reality" to the descriptions, it also gave me a sense of the inherent mutability of the model. How easy to quickly erase and write a new segement of a drawing on a white board; the issue of "this is set in stone" is completely eradicated by this technique, which reinforces the flexible nature of Ruby's object model.

While metaprogramming itself can be a touchy subject ("how much is too much?" "how do you test and maintain it?" "how do you convey what you're doing to someone picking up your code" and so on), it is such a useful thing to know. At the end, the author offers up the opinion that, in fact, metaprogramming is just programming, after all, with all the goodness and badness that can result from that if you don't pay attention to what you're doing, and more importantly, why you're doing it.

I very strongly recommend this book to Rubyists, and to others who want to discover how and why the language works as it does. Anyone coming to Ruby from another object-oriented language would do very well to pick up this book and read it thoroughly, completing the various quizzes in the first section before reading the proferred solutions, and experiment with these techniques.

Even if one never ends up using metaprogramming, the book provides such a great explanation of the object model, it is worth reading in depth.
Profile Image for Alex.
28 reviews9 followers
December 21, 2009
This is a book fills a long-standing whole in the Ruby community by laying out a cohesive explanation of the Dark Art we call "meta-programming". So much of Ruby metaprogramming is tribal knowledge and it can be difficult to acquire. Even more difficult is understanding the underlying rationale for various bits of meta-magic. This book does a good job of boiling down Ruby metaprogramming into a list of "spells", then explains each one in the context of a running narrative.

For any Ruby programming struggling to grok eigenclasses, singleton methods, dynamic dispatch and other cool tricks, this book will be your ready guide.
Profile Image for David Workman.
22 reviews13 followers
May 20, 2010
'Metaprogramming Ruby' is one of the books that has been taking the ruby programming community by force, and it is easy to see why. Metaprogramming has been espoused for quite some time as one of the most compelling features of the language, and for a lot of newcomers to the language it seems a complicated and arcane subject reserved for those who really know the hows and whys of programming in Ruby. A book that provides insights into this subject is destined for the bookshelves of rubyists everywhere as they seek to hone their Metaprogramming skills.

The book itself is written in a fairly novel fashion. It has 2 parts, the main one being composed of 5 chapters that follows a fictional week of work for a pair of ruby programmers delving into metaprogramming to solve various tasks. The 5 chapters form a fairly in-depth look at the Ruby object model, the various intricacies of it and, obviously, the metaprogramming aspects that deal with manipulating and playing around with the object model at run-time. The last day of the week is then on what most would class as quintessential metaprogramming - code that writes code.

The second (and much smaller) part of the book is about metaprogramming in rails. This is a very quick tour of some key parts of rails' design that really shows metaprogramming in action, with examples of ActiveRecord's dynamic attribute and finder methods. The book is summed up with a chapter on how to use metaprogramming safely, with examples showing how to test a class that uses metaprogramming techniques and on how to guard against unintended side-effects that are the cause of many problems.

The book as a whole is well written, with a novel and easy writing style, and it presents some fairly complex ideas in a way that is simple and accessible. If you have been programming in ruby for some time then it is likely that this book won't contain anything shockingly new but it could help to clarify some key points and help you understand Ruby better (like it has done with me). If you are a newcomer to Ruby, then the content of this book could open your eyes to a whole new vista of possibilities with Ruby and programming in general... just be careful to not over-do it :)
421 reviews83 followers
February 19, 2012
It's an impressive book that can turn an advanced programming topic like metaprogramming--which is often considered the black magic of programming--into something accessible and even easy. This book mostly pulled that off, but the way it did so was annoying: it's written as a stupid, contrived conversation between two programmers, as they learn metaprogramming.

The bizarre thing is that the second part of this book simply dumps you into the dark depths of Rails code, though accompanied by readable explanations. Probably the best part of this book is the last 12 pages, which is a summary of some common, Ruby-specific design patterns, focusing on metaprogramming. Any Ruby programmer could easily step up their game just by skimming through those 12 pages a couple times.
Profile Image for Andy Nicholson.
10 reviews3 followers
September 26, 2011
Every Ruby developer should read this book, if only to learn some of the depths of what is possible in the language, and how the ideas from different paradigms (OO, message-passing, FP) can come together with such power.

The book is conversational in tone, and the idea of "spells" discussed throughout provide helpful mnemonics to recognize the concepts in the wild later.

I read this after attempting to write Rails plugins; a lot of what seemed quite unusual to me (or sensible, if a bit quirky) now makes a lot of sense.
Profile Image for Ahmed Khattab.
35 reviews2 followers
December 28, 2022
This book was a fantastic read!. I was surprised of how much i could grasp, shadowing the skepticism i had in the start as the book is a bit old.

But fear not. It contains verbose explanation of Ruby's Metaprogramming tools. How Ruby allows you to do black magic!.
Profile Image for Azzen Abidi.
21 reviews2 followers
June 2, 2020
I picked up this book hoping I would satisfy my curiosity about DSL, ORM, and the inner mechanics of the Ruby On Rails Framework. Let me just say the book exceeded my expectations. It doesn't only show the magic of the Ruby language, it also goes deep into metaprogramming and how it can be leveraged to solve some classic programming and software design problems.

However, I didn't very much like the storytelling element and the absence of a complete real project to grasp the fundamentals of metaprogramming.

Overall, the book is good. It certainly delivers. I won't recommend it to beginners though. There will be a steep learning curve. But, if you have enough time and curiosity, go ahead.
Profile Image for Jason.
350 reviews14 followers
January 11, 2020
The narrative writing style of "let's pretend it's your first week on the job" felt kind of odd, but as far as material it's exactly what I was looking for: starting to understand the nuts and bolts of how Ruby works under the hood.
3 reviews1 follower
February 6, 2014
I will be rereading this book periodically to keep my Ruby skills sharp. It clarified concepts I was familiar with (Eigenclass and class_eval) and instructs on how to skillfully use them. He uses examples from several popular projects. He knows his stuff.

I was impressed with the list of spells (ie design patterns) he used. They are:

Argument Array
Collapse a list of arguments into an array.

Around Alias
Call the previous, aliased version of a method from a redefined method.

Blank Slate
Remove methods from an object to turn them into Ghost Methods.

Class Extension
Define class methods by mixing a module into a class's eigenclass.

Class Extension Mixin
Enable a module to extend is include through a Hook Method.

Class Instance Variable
Store class-level state in an instance variable of the Class object.

Class Macro
Use a class method in a class definition.

Clean Room
Use an object as an environment in which to evaluate a block.

Code Processor
Process a String of Code from an external source.

Context Probe
Execute a block to access information in an object's context.

Deferred Evaluation
Fore a piece of code and its context in a proc or lambda for evaluation later.

Dynamic Dispatch
Decide which method to call at runtime.

Dynamic Method
Decide how to define a method at runtime.

Dynamic Proxy
Forwad to another object any messages that don't match a method.

Flat Scope
Use a closure to share variable between two scopes.

Ghost Method
Respond to a message that doesn't have an associated method.

Hook Method
Override a method to intercept object model events.

Kernal Method
Define a method in module Kernal to make the method available to all objects.

Lazy Instance Variable
Wait until the first access to initialize an instance variable.

Mimic Method
Disguise a method as another language contruct.

Monkey patch
Change the features of an existing class.

Named Arguments
Collect method arguments into a hash to identify them by name.

Namespace
Define constants within a module to avoid name clashes.

Nil Guard
Override a reference to nil with an ||

Object Extension
Define Singleton Methods by mixing a module into an object's eigenclass.

Open Class
Modify an existing class.

Pattern Dispatch
Select which methods to call based on their names.

Sandbox
Execute untrusted code in a safe environment.

Scope Gate
Isolate a scope with the class, module, or def keyword.

Shared Scope
Share variables among multiple contexts in the same Flat Scope.

Singleton Method
Define a method on a single object

String of Code
Evaluate a string of Ruby code.

Symbol to Proc
Convert a symbo to a block that calls a single method.
3 reviews1 follower
September 7, 2016
I will be rereading this book periodically to keep my Ruby skills sharp. It clarified concepts I was familiar with (Eigenclass and class_eval) and instructs on how to skillfully use them. He uses examples from several popular projects. He knows his stuff.

I was impressed with the list of spells (ie design patterns) he used. They are:

Argument Array
Collapse a list of arguments into an array.

Around Alias
Call the previous, aliased version of a method from a redefined method.

Blank Slate
Remove methods from an object to turn them into Ghost Methods.

Class Extension
Define class methods by mixing a module into a class's eigenclass.

Class Extension Mixin
Enable a module to extend is include through a Hook Method.

Class Instance Variable
Store class-level state in an instance variable of the Class object.

Class Macro
Use a class method in a class definition.

Clean Room
Use an object as an environment in which to evaluate a block.

Code Processor
Process a String of Code from an external source.

Context Probe
Execute a block to access information in an object's context.

Deferred Evaluation
Fore a piece of code and its context in a proc or lambda for evaluation later.

Dynamic Dispatch
Decide which method to call at runtime.

Dynamic Method
Decide how to define a method at runtime.

Dynamic Proxy
Forwad to another object any messages that don't match a method.

Flat Scope
Use a closure to share variable between two scopes.

Ghost Method
Respond to a message that doesn't have an associated method.

Hook Method
Override a method to intercept object model events.

Kernal Method
Define a method in module Kernal to make the method available to all objects.

Lazy Instance Variable
Wait until the first access to initialize an instance variable.

Mimic Method
Disguise a method as another language contruct.

Monkey patch
Change the features of an existing class.

Named Arguments
Collect method arguments into a hash to identify them by name.

Namespace
Define constants within a module to avoid name clashes.

Nil Guard
Override a reference to nil with an ||

Object Extension
Define Singleton Methods by mixing a module into an object's eigenclass.

Open Class
Modify an existing class.

Pattern Dispatch
Select which methods to call based on their names.

Sandbox
Execute untrusted code in a safe environment.

Scope Gate
Isolate a scope with the class, module, or def keyword.

Shared Scope
Share variables among multiple contexts in the same Flat Scope.

Singleton Method
Define a method on a single object

String of Code
Evaluate a string of Ruby code.

Symbol to Proc
Convert a symbo to a block that calls a single method.
Profile Image for Pasha Muravyev.
3 reviews3 followers
August 13, 2013
Awesome book, all around. The first few chapters were fairly easy to follow, and I enjoyed some of the humorous "pair-programming" dialogue that was sprinkled into the story. While reading the book, I had a lot of Ah-ha! moments, when I finally pieces something together which I had learned from a slew of different sources, but never really integrated into a common whole. Metaprogramming Ruby does a really good job of taking knowledge that you might have picked up from a variety of different sources and showing you how it all works together to create the magic that we commonly see in Ruby programs.

The last three chapters deal with dynamic attribute methods and dynamic finders in ActiveRecord - and I was quite surprised that I could grok the content of those chapters. I've attempted looking at the Rails source on my own before, but the amount of metaprogramming in its core has always stumped me; this book does a really nice job of holding your hand through the "magic" of metaprogramming so that you can dig into the ideas hidden behind the syntax: how instance_eval is simply a convenience method for opening up the eigenclass (of a class or object) or using a scope probe to execute some code in a binding.

The spell book is an awesome bonus too - a single point of reference for most techniques described in the book. 5/5 - I will probably end up reading this again at some point! If you want to really improve your ruby chops, you have absolutely no excuse not to read this book (unless your name is Chad Fowler).
54 reviews4 followers
August 1, 2010
Metaprogramming Ruby is by far my favorite Ruby book. First, it does not treat the reader as a brand new programmer. The basics of Ruby are obvious to anyone that has programmed before, and can be picked up as examples are given. Thankfully this is not included in this book. What is included are the main differences between Ruby and other object-oriented languages such as Java, Python, and C++. This is an area which most other Ruby books completely lack.

If you are curious how Ruby pulls off it's magic (particularly if you are amazed at the tricks in Rails or ActiveRecord), or just wish to leverage Ruby's strongest features, then this is the book you want to pick up. If you are new to Ruby, but not to programming, start with Metaprogramming Ruby. It is much more succinct and useful (the summary of "spells" at the end of the book is gold) than the much longer The Ruby Way or Pick Axe.

Why not 5 stars? The author's boss-employee schtick to explain the concepts along with the excessive amount of lame nerd humor got a bit annoying and for me took away from an otherwise excellent read.
13 reviews
October 11, 2012
The author creates a continuing story as a framework around which to present the material. I found the narrative annoying, and therefore distracting, so much so that I had to abandon reading it after the second chapter.

However, material presented is sound, if you can get past the cutesy presentation. Otherwise covers metaprogramming in ruby well in - highly recommended.
Profile Image for Brian.
658 reviews288 followers
November 2, 2012
(4.0) Pretty good resource

Most valuable part for me was just walking through the ruby object model in a structured way (rather than just poking at it to learn in irb). Then the metaprogramming concepts build well on top of that. I definitely learned a lot. Though I think it should be emphasized more that metaprogramming can create more problems than it solves and should be looked as an option (vs. writing a bunch more code that's more clear). I'll probably refer back to it when developing gems and such.
6 reviews3 followers
December 6, 2012
I didn't read this book, I actually studied it!
If you consider yourself Senior on Ruby this book should be a recap on what you already know and some new tricks will get to you.
If you are a Ruby newcomer then meta-programming is a must know if you want to become a decent rubyist and this book is an easy way to start getting there.

I compiled a few quizzes mostly out of this book like i usually do:
15 reviews
September 10, 2011
Really good introduction to the metaprogramming capabilities of Ruby. It's quite an easy read as the author wrote the book as a conversation between two developers (this is taken a bit to the extreme in a few places of the book).

I think this is an excellent book for someone who doesn't have any background on the metaprogramming features of ruby.
Profile Image for Davinici.
17 reviews
March 14, 2012
Good book on meta programming. The writing style starts of kind of quirky as a dialogue between an old experienced programmer and his apprentice. This quickly got old for me though, whilst it reads easily it is a longhand form of getting ideas across, and makes it harder to skim content.

The second part of the book, examines portions of the rails source code, namely activerecord.
Profile Image for Michael.
193 reviews
April 17, 2013
The first half of the book employs a 2nd-person narrative point of view that takes some getting used to. I would have disliked it more has I not been forewarned by other reviewers. Though tedious at first, ultimately I think it worked well to present concepts that are then studied in real world applications in the second half of the book.
16 reviews
July 20, 2016
I really enjoyed this book. There are a lot of great tip and tools to learn from it as well as concrete examples. There is also a great recap of the "Spells" learned along the way in the Appendix. Which will be handy when one needs to recap an technique.
Profile Image for Dale.
540 reviews68 followers
October 2, 2013
This is a nice compendium of ruby metaprogramming techniques, and worth having on your shelf. My biggest criticism is that it's very repetitive: the same technique is shown under different headings, and then it's all repeated again in an appendix.
37 reviews1 follower
September 26, 2012
A must read for any Ruby programmer!
It gives you an overview of the object model in the first couple of chapters and suddenly every single line of code that didn't make much sense in popular libraries is clear as an A class diamond :)
Profile Image for Ibrahim.
3 reviews7 followers
February 17, 2013
This is the most comprehensive resource I have seen on Metaprogramming in Ruby. Its easy to read for a more advanced topic. Explains how a number of great Ruby gems work. I feel I am a way more capable Ruby Programmer after reading it.
Profile Image for Akash Agrawal.
2 reviews
March 5, 2013
An awesome book for those who have already wet there feet in ruby and are now itching to expand their knowledge. It not only teaches you metaprogramming, but the innards of ruby itself. As the author puts it, "Metaprogramming is everywhere in Ruby".
9 reviews2 followers
February 9, 2015
Terrific book that covers the complete Ruby object model and various patterns and techniques that you can use to manipulate it.

I've been writing Ruby for almost a decade without knowing most of this. I so wish I'd read this sooner.
1 review1 follower
November 6, 2010
Отличная книжка, которая помогла систематизировать текущие знания.
Profile Image for EJ.
13 reviews7 followers
June 14, 2011
Really great look at how to really manipulate the Ruby language to do what you need.
Profile Image for Paul Barry.
5 reviews14 followers
March 9, 2011
Excellent book, gives clear, practical examples of how you can use metaprogramming in Ruby to make better programs
Displaying 1 - 30 of 45 reviews

Can't find what you're looking for?

Get help and learn more about the design.