100% found this document useful (13 votes)
64 views

Metaprogramming Ruby program like the Ruby pros 1st Edition Paolo Perrotta 2024 Scribd Download

Paolo

Uploaded by

dafoelascojw
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (13 votes)
64 views

Metaprogramming Ruby program like the Ruby pros 1st Edition Paolo Perrotta 2024 Scribd Download

Paolo

Uploaded by

dafoelascojw
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 50

Download the full version of the ebook at ebookname.

com

Metaprogramming Ruby program like the Ruby pros


1st Edition Paolo Perrotta

https://ebookname.com/product/metaprogramming-ruby-program-
like-the-ruby-pros-1st-edition-paolo-perrotta/

OR CLICK BUTTON

DOWNLOAD EBOOK

Download more ebook instantly today at https://ebookname.com


Instant digital products (PDF, ePub, MOBI) available
Download now and explore formats that suit you...

The Ruby Way Solutions and Techniques in Ruby Programming


Second Edition Desconocido

https://ebookname.com/product/the-ruby-way-solutions-and-techniques-
in-ruby-programming-second-edition-desconocido/

ebookname.com

Ruby for Rails Ruby techniques for Rails developers David


Black

https://ebookname.com/product/ruby-for-rails-ruby-techniques-for-
rails-developers-david-black/

ebookname.com

Ruby Pocket Reference 2nd Edition Instant Help for Ruby


Programmers Michael Fitzgerald

https://ebookname.com/product/ruby-pocket-reference-2nd-edition-
instant-help-for-ruby-programmers-michael-fitzgerald/

ebookname.com

Fulke Greville Lord Brooke 1554 1628 Joan Rees

https://ebookname.com/product/fulke-greville-lord-
brooke-1554-1628-joan-rees/

ebookname.com
Sticky Faith Youth Worker Edition Practical Ideas to
Nurture Long Term Faith in Teenagers Kara Powell & Brad M.
Griffin & Cheryl A. Crawford
https://ebookname.com/product/sticky-faith-youth-worker-edition-
practical-ideas-to-nurture-long-term-faith-in-teenagers-kara-powell-
brad-m-griffin-cheryl-a-crawford/
ebookname.com

Pygmalion Webster s Thesaurus Edition George Bernard Shaw

https://ebookname.com/product/pygmalion-webster-s-thesaurus-edition-
george-bernard-shaw/

ebookname.com

Radiowave propagation and antennas for personal


communications 3rd Edition Kazimierz Siwiak

https://ebookname.com/product/radiowave-propagation-and-antennas-for-
personal-communications-3rd-edition-kazimierz-siwiak/

ebookname.com

Enterprise Cybersecurity How to Build a Successful


Cyberdefense Program Against Advanced Threats 1st Edition
Scott E. Donaldson
https://ebookname.com/product/enterprise-cybersecurity-how-to-build-a-
successful-cyberdefense-program-against-advanced-threats-1st-edition-
scott-e-donaldson/
ebookname.com

The Complete Idiot s Guide to Persuasion 1st Edition Ed.D.

https://ebookname.com/product/the-complete-idiot-s-guide-to-
persuasion-1st-edition-ed-d/

ebookname.com
Mathematical Physics Applied Mathematics for Scientists
and Engineers Second Edition Bruce R. Kusse

https://ebookname.com/product/mathematical-physics-applied-
mathematics-for-scientists-and-engineers-second-edition-bruce-r-kusse/

ebookname.com
What Readers Are Saying About Metaprogramming Ruby

Reading this book was like diving into a new world of thinking. I tried
a mix of Java and JRuby metaprogramming on a recent project. Using
Java alone would now feel like entering a sword fight carrying only
a banana, when my opponent is wielding a one-meter-long Samurai
blade.
Sebastian Hennebrüder
Java Consultant and Trainer, laliluna.de

This Ruby book fills a gap between language reference manuals and
programming cookbooks. Not only does it explain various meta-
programming facilities, but it also shows a pragmatic way of making
software smaller and better. There’s a caveat, though; when the new
knowledge sinks in, programming in more mainstream languages will
start feeling like a chore.
Jurek Husakowski
Software Designer, Philips Applied Technologies

Before this book, I’d never found a clear organization and explanation
of concepts like the Ruby object model, closures, DSLs definition, and
eigenclasses all spiced with real-life examples taken from the gems we
usually use every day. This book is definitely worth reading.
Carlo Pecchia
Software Engineer

I’ve had a lot of trouble finding a good way to pick up these meta-
programming techniques, and this book is bar none the best way to
do it. Paolo Perrotta makes it painless to learn Ruby’s most complex
secrets and use them in practical applications.
Chris Bunch
Software Engineer
Metaprogramming Ruby
Program Like the Ruby Pros

Paolo Perrotta

The Pragmatic Bookshelf


Raleigh, North Carolina Dallas, Texas
Many of the designations used by manufacturers and sellers to distinguish their prod-
ucts are claimed as trademarks. Where those designations appear in this book, and The
Pragmatic Programmers, LLC was aware of a trademark claim, the designations have
been printed in initial capital letters or in all capitals. The Pragmatic Starter Kit, The
Pragmatic Programmer, Pragmatic Programming, Pragmatic Bookshelf and the linking g
device are trademarks of The Pragmatic Programmers, LLC.

Every precaution was taken in the preparation of this book. However, the publisher
assumes no responsibility for errors or omissions, or for damages that may result from
the use of information (including program listings) contained herein.

Our Pragmatic courses, workshops, and other products can help you and your team
create better software and have more fun. For more information, as well as the latest
Pragmatic titles, please visit us at

http://www.pragprog.com

Copyright © 2010 Paolo Perrotta.

All rights reserved.

No part of this publication may be reproduced, stored in a retrieval system, or transmit-


ted, in any form, or by any means, electronic, mechanical, photocopying, recording, or
otherwise, without the prior consent of the publisher.

Printed in the United States of America.

ISBN-10: 1-934356-47-6
ISBN-13: 978-1-934356-47-0
Printed on acid-free paper.
P1.0 printing, January 2010
Version: 2010-1-29
To Carlo.
Contents
Foreword 10

Acknowledgments 11

Introduction 13
The “M” Word . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
About This Book . . . . . . . . . . . . . . . . . . . . . . . . . . 21
About You . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24

I Metaprogramming Ruby 26

1 Monday: The Object Model 27


1.1 Monday with Bill . . . . . . . . . . . . . . . . . . . . . . 27
1.2 Open Classes . . . . . . . . . . . . . . . . . . . . . . . . 28
1.3 The Truth About Classes . . . . . . . . . . . . . . . . . . 33
1.4 Quiz: Missing Lines . . . . . . . . . . . . . . . . . . . . . 45
1.5 What Happens When You Call a Method? . . . . . . . . 46
1.6 Quiz: Tangle of Modules . . . . . . . . . . . . . . . . . . 56
1.7 Object Model Wrap-Up . . . . . . . . . . . . . . . . . . . 59

2 Tuesday: Methods 60
2.1 A Duplication Problem . . . . . . . . . . . . . . . . . . . 61
2.2 Dynamic Methods . . . . . . . . . . . . . . . . . . . . . . 63
2.3 method_missing() . . . . . . . . . . . . . . . . . . . . . . 71
2.4 Quiz: Bug Hunt . . . . . . . . . . . . . . . . . . . . . . . 82
2.5 More method_missing() . . . . . . . . . . . . . . . . . . . 84

3 Wednesday: Blocks 91
3.1 How to Handle Hump Day . . . . . . . . . . . . . . . . . 92
3.2 Quiz: Ruby# . . . . . . . . . . . . . . . . . . . . . . . . . 93
3.3 Closures . . . . . . . . . . . . . . . . . . . . . . . . . . . 96
3.4 instance_eval() . . . . . . . . . . . . . . . . . . . . . . . . 105
CONTENTS 8

3.5 Callable Objects . . . . . . . . . . . . . . . . . . . . . . . 108


3.6 Writing a Domain-Specific Language . . . . . . . . . . . 116
3.7 Quiz: A Better DSL . . . . . . . . . . . . . . . . . . . . . 118

4 Thursday: Class Definitions 122


4.1 Class Definitions Demystified . . . . . . . . . . . . . . . 123
4.2 Quiz: Class Taboo . . . . . . . . . . . . . . . . . . . . . . 130
4.3 Singleton Methods . . . . . . . . . . . . . . . . . . . . . 132
4.4 Eigenclasses . . . . . . . . . . . . . . . . . . . . . . . . . 137
4.5 Quiz: Module Trouble . . . . . . . . . . . . . . . . . . . 150
4.6 Aliases . . . . . . . . . . . . . . . . . . . . . . . . . . . . 152
4.7 Quiz: Broken Math . . . . . . . . . . . . . . . . . . . . . 157

5 Friday: Code That Writes Code 160


5.1 Leading the Way . . . . . . . . . . . . . . . . . . . . . . . 160
5.2 Kernel#eval . . . . . . . . . . . . . . . . . . . . . . . . . 163
5.3 Quiz: Checked Attributes (Step 1) . . . . . . . . . . . . 173
5.4 Quiz: Checked Attributes (Step 2) . . . . . . . . . . . . 176
5.5 Quiz: Checked Attributes (Step 3) . . . . . . . . . . . . 178
5.6 Quiz: Checked Attributes (Step 4) . . . . . . . . . . . . 179
5.7 Hook Methods . . . . . . . . . . . . . . . . . . . . . . . . 180
5.8 Quiz: Checked Attributes (Step 5) . . . . . . . . . . . . 186

6 Epilogue 188

II Metaprogramming in Rails 189

7 The Design of ActiveRecord 190


7.1 Preparing for the Tour . . . . . . . . . . . . . . . . . . . 191
7.2 The Design of ActiveRecord . . . . . . . . . . . . . . . . 193
7.3 Lessons Learned . . . . . . . . . . . . . . . . . . . . . . 202

8 Inside ActiveRecord 206


8.1 Dynamic Attributes . . . . . . . . . . . . . . . . . . . . . 206
8.2 Dynamic Finders . . . . . . . . . . . . . . . . . . . . . . 214
8.3 Lessons Learned . . . . . . . . . . . . . . . . . . . . . . 219

9 Metaprogramming Safely 224


9.1 Testing Metaprogramming . . . . . . . . . . . . . . . . . 224
9.2 Defusing Monkeypatches . . . . . . . . . . . . . . . . . 232
9.3 Lessons Learned . . . . . . . . . . . . . . . . . . . . . . 237
CONTENTS 9

III Appendixes 239

A Common Idioms 240


A.1 Mimic Methods . . . . . . . . . . . . . . . . . . . . . . . 240
A.2 Nil Guards . . . . . . . . . . . . . . . . . . . . . . . . . . 243
A.3 Tricks with Method Arguments . . . . . . . . . . . . . . 244
A.4 Self Yield . . . . . . . . . . . . . . . . . . . . . . . . . . . 248
A.5 Symbol#to_proc() . . . . . . . . . . . . . . . . . . . . . . 249

B Domain-Specific Languages 252


B.1 The Case for Domain-Specific Languages . . . . . . . . 252
B.2 Internal and External DSLs . . . . . . . . . . . . . . . . 254
B.3 DSLs and Metaprogramming . . . . . . . . . . . . . . . 255

C Spell Book 256


C.1 The Spells . . . . . . . . . . . . . . . . . . . . . . . . . . 256

D Bibliography 268

Index 269
Foreword
Ruby inherits characteristics from various languages — Lisp, Small-
talk, C, and Perl, to name a few. Metaprogramming comes from Lisp
(and Smalltalk). It’s a bit like magic, which makes something astonish-
ing possible. There are two kinds of magic: white magic, which does
good things, and black magic, which can do nasty things. Likewise,
there are two aspects to metaprogramming. If you discipline yourself,
you can do good things, such as enhancing the language without
tweaking its syntax by macros or enabling internal domain-specific
languages. But you can fall into the dark side of metaprogramming.
Metaprogramming can confuse easily.
Ruby trusts you. Ruby treats you as a grown-up programmer. It gives
you great power such as metaprogramming. But you need to remember
that with great power comes great responsibility.
Enjoy programming in Ruby.

matz
October 2009
Acknowledgments
Before I begin, I need to thank a few people. I’m talking to you, gen-
tlemen: Joe Armstrong, Satoshi Asakawa, Paul Barry, Emmanuel Ber-
nard, Roberto Bettazzoni, Ola Bini, Piergiuliano Bossi, Simone Busoli,
Andrea Cisternino, Davide D’Alto, Mauro Di Nuzzo, Marco Di Timo-
teo, Mauricio Fernandez, Jay Fields, Michele Finelli, Neal Ford, Flo-
rian Frank, Sanne Grinovero, Federico Gobbo, Florian Groß, Sebastian
Hennebrüder, Doug Hudson, Jurek Husakowski, Lyle Johnson, Luca
Marchetti, MenTaLguY, Carlo Pecchia, Andrea Provaglio, Mike Roberts,
Martin Rodgers, Jeremy Sydik, Andrea Tomasini, Marco Trincardi, Ivan
Vaghi, Giancarlo Valente, Davide Varvello, Jim Weirich, and the dozens
of readers who reported problems and errata while this book was in
beta. Whether you provided reviews, quotes, fixes, opinions, or moral
support, there’s at least one line in this book that changed for the bet-
ter because of you. Did I say one line? For some of you, make that “a
few chapters.” In particular, Ola, Satoshi, and Jurek deserve a special
place on this page and my enduring gratitude.
Thanks to the staff at the Pragmatic Bookshelf: Janet Furlow, Seth
Maislin, Steve Peter, Susannah Davidson Pfalzer, and Kim Wimpsett.
Dave and Andy, thank you for believing in this project when times got
rough. Jill, thank you for making my awkward prose look so effortless.
Our crunch week in Venice was a lot of hard work, but it was definitely
worth it. And speaking of Venice: thank you, Lucio, for being such a
dear old friend.
Mom and Dad, thank you for your support, for your love, and for never
asking why I was taking so long to finish this book.
Most authors’ closing thanks go to their partners, and now I know why.
When you’re about to finish a book, you turn back to the day when
you started writing, and it feels so far away. I remember writing over
lunch breaks, nights, and weekends, locked for days or weeks inside
A CKNOWLEDGMENTS 12

my study, a hotel room in some foreign city, or a seashore house that


would have suited a hermit. It’s such a lonesome endeavor—and yet, I
never felt alone. Thank you, Mirella.
Will write code that writes code that writes code for food.
Martin Rodgers

Introduction
Metaprogramming. . . it sounds cool! It sounds like a design technique
for high-level enterprise architects or a fashionable buzzword that has
found its way into press releases.
In fact, far from being an abstract concept or a bit of marketing-speak,
metaprogramming is a collection of down-to-earth, pragmatic coding
techniques. It doesn’t just sound cool; it is cool. Here are some of the
things you can do with metaprogramming in the Ruby language:
• Say you want to write a Ruby program that connects to an external
system—maybe a web service or a Java program. With metapro-
gramming, you can write a wrapper that takes any method call
and routes it to the external system. If somebody adds methods
to the external system later, you don’t have to change your Ruby
wrapper; the wrapper will support the new methods right away.
That’s magic!
• Maybe you have a problem that would be best solved with a pro-
gramming language that’s specific to that problem. You could go
to the trouble of writing your own language, custom parser and
all. Or you could just use Ruby, bending its syntax until it looks
like a specific language for your problem. You can even write your
own little interpreter that reads code written in your Ruby-based
language from a file.
• You can remove duplication from your Ruby program at a level
that Java programmers can only dream of. Let’s say you have
twenty methods in a class, and they all look the same. How about
defining all those methods at once, with just a few lines of code?
Or maybe you want to call a sequence of similarly named meth-
ods. How would you like a single short line of code that calls all
the methods whose names match a pattern—like, say, all methods
that begin with test?
T HE “M” W ORD 14

• You can stretch and twist Ruby to meet your needs, rather than
adapt to the language as it is. For example, you can enhance any
class (even a core class like Array) with that method you miss so
dearly, you can wrap logging functionality around a method that
you want to monitor, you can execute custom code whenever a
client inherits from your favorite class. . . the list goes on. You are
limited only by your own, undoubtedly fertile, imagination.
Metaprogramming gives you the power to do all these things. Let’s see
what it looks like.

The “M” Word


You’re probably expecting a definition of metaprogramming right from
the start. Here’s one for you:
Metaprogramming is writing code that writes code.
We’ll get to a more precise definition in a short while, but this one will
do for now. What do I mean by “code that writes code,” and how is that
useful in your daily work? Before I answer those questions, let’s take a
step back and look at programming languages themselves.

Ghost Towns and Marketplaces


Think of your source code as a world teeming with vibrant citizens:
variables, classes, methods, and so on. If you want to get technical,
you can call these citizens language constructs.
In many programming languages, language constructs behave more
like ghosts than fleshed-out citizens: you can see them in your source
code, but they disappear before the program runs. Take C++, for exam-
ple. Once the compiler has finished its job, things like variable and
method have lost their concreteness; they are just locations in mem-
ory. You can’t ask a class for its instance methods, because by the time
you ask the question, the class has faded away. In languages like C++,
runtime is an eerily quiet place—a ghost town.
In other languages, such as Ruby, runtime looks more like a busy mar-
ketplace. Most language constructs are still there, buzzing all around.
You can even walk up to a construct and ask it questions about itself.
This is called introspection. Let’s watch introspection in action.
T HE “M” W ORD 15

Code Generators and Compilers


In metaprogramming, you write code that writes code. But isn’t
that what code generators and compilers do? For example,
you can write annotated Java code and then use a code gen-
erator to output XML configuration files. In a broad sense, this
XML generation is an example of metaprogramming. In fact,
many people think about code generation when the “m” word
comes up.
This particular brand of metaprogramming implies that you use
a program to generate or otherwise manipulate a second, dis-
tinct program—and then you run the second program. After
you run the code generator, you can actually read the gener-
ated code and (if you want to test your tolerance for pain) even
modify it by hand before you finally run it. This is also what hap-
pens under the hood with C++ templates: the compiler turns
your templates into a regular C++ program before compiling
them, and then you run the compiled program.
In this book, I’ll stick to a different meaning of metaprogram-
ming, focusing on code that manipulates itself at runtime. Only
a few languages can do that effectively, and Ruby is one of
them. You can think of this as dynamic metaprogramming to
distinguish it from the static metaprogramming of code gener-
ators and compilers.

Introspection
Take a look at this code:
Download introduction/introspection.rb

class Greeting
def initialize(text)
@text = text
end

def welcome
@text
end
end

my_object = Greeting.new("Hello" )

I defined a Greeting class and created a Greeting object. I can now turn
to the language constructs and ask them questions.
Exploring the Variety of Random
Documents with Different Content
ACANTHORHYNCHUS TENUIROSTRIS.
Slender-billed Spine-bill.

Certhia tenuirostris, Lath. Ind. Orn. Suppl., p. xxxvi.


Le Cap noir, Vieill. Ois. Dor., tom. ii. p. 94. pl. 60.
Slender-billed Honey-eater, Lath. Gen. Hist., vol. iv. p. 194. pl.
lxii.
Flapping Honey-eater, Lath. Gen. Hist., vol. iv. p. 195.
Hooded Creeper, Shaw, Gen. Zool., vol. viii. p. 109.
Slender-billed Creeper, Lath. Gen. Syn. Suppl., vol. ii. p. 165. pl.
129.
Meliphaga tenuirostris, Vig. and Horsf. in Linn. Trans., vol. xv.
p. 317.
Acanthorhynchus tenuirostris, Gould, Syn. Birds of Australia,
Part II.
—— dubius? Gould in Proc. of Zool. Soc., Part V. p. 25; and in
Syn. Birds of Australia, Part II.
Cobbler’s Awl, Colonists of Van Diemen’s Land.
Spine-bill, Colonists of New South Wales.

On referring to the above list of synonyms, it will be seen that I


formerly entertained an opinion that there were two species of this
genus very nearly allied to each other, the one a native of Van
Diemen’s Land, and the other of the continent of Australia; the
former being distinguished from the latter by its smaller size in all its
admeasurements, by the crescent-shaped markings of the neck, and
by the brown of the abdomen being much deeper in colour; I am
now, however, inclined to believe that they are identical; but as no
conclusive evidence that such is the case has yet been obtained, I
must leave the matter still doubtful until further research shall
enable us to decide the question. In habits, disposition and
nidification the two birds closely assimilate, as I had abundant
opportunities of observing during my residence in the colonies.
There is no member of the large family of Honey-eaters to which it
belongs that enjoys a structure more especially adapted for the
purposes of its existence than the present species, whose fine and
extremely delicate bill is peculiarly suited for the extraction of insects
and honey from the inmost recesses of the tubular flowers which
abound in many parts of Australia, particularly of the various species
of Epacris, a tribe of plants closely allied to the Heaths (Erica) of
Africa and Europe, which when in bloom are always frequented by
numbers of these birds, so much so indeed that it would seem as if
the one was expressly designed for the other, the flowers for the birds
and vice versâ; those who have traversed the immense beds of
Epacris impressa, so abundant in Van Diemen’s Land, must have
often observed the bird darting out from beneath his feet and flitting
off to a very short distance, descending again to the thickest parts of
the beds. It also frequents the wattles and gums during their
flowering-season, and appears to be attracted to their blossoms quite
as much for the insects as for the nectar, the stomachs of all those
dissected containing the remains of coleoptera and other insects. It is
rather shy in disposition except when closely engaged in procuring
food, when it may be approached within a yard or two.
Its flight is extremely quick and darting and performed with a
zigzag motion; and its note, which is a monotonous shriek, is
somewhat loud for so small a bird. Should the bird to which I have
given the name of dubius prove to be merely a local variety, this
species will be found to range over a wide extent of country,
including Van Diemen’s Land, all the islands in Bass’s Straits, and
the continent of Australia from South Australia to Moreton Bay; to
the eastward of the former, or to the eastward and northward of the
latter country, I have never been able to trace it.
The nest of this species is a small cup-shaped and rather beautiful
structure, although not so compact or neatly formed as that of many
other birds; those I found, both in Van Diemen’s Land and New
South Wales, were built on some low shrubs a few feet from the
ground, mostly in a species of Leptospermum; it is outwardly
constructed of moss and grasses, and lined with feathers; the eggs
are two in number, of a delicate huffy white, increasing in depth of
colour towards the larger end; in some instances I have found them
marked with a zone of reddish chestnut spots shaded with indistinct
markings of grey, intermingled with very minute ink-like dots; in
form the eggs are much lengthened and pointed; their medium
length is nine lines and breadth six lines.
Crown of the head shining greenish black; space between the bill
and the eye, ear-coverts, lunated band on the sides of the chest,
primaries, and six middle tail-feathers black; the remainder of the
tail-feathers black largely tipped with white, and slightly margined
on the external web with brown; back of the neck rufous chestnut,
passing into chestnut-brown on the upper part of the back;
secondaries, greater wing-coverts, rump and upper tail-coverts grey;
throat, cheeks and chest white, the first with a patch of chestnut-
brown in the centre, deepening into black on its lower edge;
abdomen, flanks and under tail-coverts light chestnut-brown; irides
scarlet; bill black; feet reddish brown.
Specimens from Van Diemen’s Land have the patch in the centre
of the throat and the lunated marks on the sides of the neck much
deeper and the whole of the under surface richer chestnut.
The figures are those of a male and female, on a branch of what is
considered a white variety of Epacris impressa.
ACANTHORHYNCHUS
SUPERCILIOSUS:
Gould.

J. Gould
and H. C.
Richter del
et lith.
C.
Hullmandel
Imp.
ACANTHORHYNCHUS SUPERCILIOSUS,
Gould.
White-eyebrowed Spine-bill.

Acanthorhynchus superciliosus, Gould in Proc. of Zool. Soc., Part


V. p. 24.
Bool-jeet, Aborigines of the lowland districts of Western
Australia.

Hitherto I have only received this fine and well-marked species of


Spine-billed Honey-eater from Western Australia, but hereafter it
will doubtless be found to range over a much greater extent of
country; although a very local bird, it is tolerably abundant both at
Swan River and King George’s Sound, and is found to give a decided
preference to the forests of Banksias, upon the blossoms of which
trees it almost solely subsists. Its food, like that of the other members
of its family, consists of insects and honey, for obtaining which its
delicately organized bill and the filamentous form of its tongue are
peculiarly adapted; the latter member being capable of considerable
protrusion beyond the apex of the bill, thus enabling the bird to dive
into the deepest interstices of the flowers, which its bill alone would
not permit. Like its congeners, this species occasionally frequents the
low shrub-like trees, and sometimes is even to be observed upon the
ground in search of food. In its actions it displays great activity,
darting about from branch to branch with a rapid zigzag motion; its
flight is irregular and uneven, but it often rises perpendicularly in the
air, uttering at the same time a rather pretty song; at others it emits a
loud and strong note.
The nest, which is constructed among the large-leaved Banksias, is
of a round compact form, and is composed of dried fine grasses,
tendrils of flowers, narrow threads of bark and fine wiry fibrous roots
matted together with zamia wool, forming a thick body, which is
warmly lined with feathers and zamia wool mingled together; the
external diameter of the nest is three inches, and that of the cavity
about one inch and a quarter. The eggs are two in number, nine lines
long by six and a half broad; their ground colour in some instances is
a delicate buff, in others a very delicate bluish white with a few
specks of reddish brown distributed over the surface, these specks
being most numerous at the larger end, where they frequently
assume the form of a zone. The breeding-season is in October.
The sexes present little or no difference in external appearance,
but the female may generally be distinguished from her mate by her
more diminutive size and the more slender contour of her body.
Crown of the head, all the upper surface, wings, and six middle
tail-feathers greyish brown, the remainder of the tail-feathers black,
largely tipped with white and narrowly margined on their external
edges with brown; space between the bill and eye, and the ear-
coverts blackish brown; stripe over the eye, chin, and a broader
stripe beneath the eye white; back part of the neck light chestnut-
brown; centre of the throat rich chestnut, bounded below by a
crescent of white, which is succeeded by another of black; abdomen
and under tail-coverts light greyish brown, in some specimens
deepening into buff; irides reddish brown; bill black; legs dark
brown.
The figures are those of a male and a female of the natural size.
MYZOMELA
SANGUINOLENTA.

J. Gould
and H. C.
Richter del
et lith.
C.
Hullmandel
Imp.
MYZOMELA SANGUINOLENTA.
Sanguineous Honey-eater.

Certhia sanguinolenta, Lath. Ind. Orn. Supp., p. xxxvii.


L’Heorotaire sanguin, Vieill. Ois. Dor., tom. ii. p. 127.
Sanguineous Creeper, Lath. Gen. Syn. Supp., vol. ii. p. 167. pl.
130.—Shaw, Gen. Zool., vol. viii. p. 235.
Sanguineous Honey-eater, Lath. Gen. Hist., vol iv. p. 201. pl. 73.
Certhia dibapha, Lath. Ind. Orn. Supp., p. xxxvii.
L’Heorotaire rouge tacheté, Vieill. Ois. Dor., tom. ii. p. 127.
Small-crested Creeper, Shaw, Gen. Zool., vol. viii. p. 253. pl. 35?
Cochineal Creeper, Lath. Gen. Syn. Supp., vol. ii. p. 167.
Cochineal Honey-eater, Lath. Gen. Hist., vol. iv. p. 201.
Certhia erythropygia, Lath. Ind. Orn. Supp., p. 38.
Red-rumped Creeper, Lath. Gen. Syn. Supp., vol. ii. p. 169.—
Shaw, Gen. Zool. vol. viii. p. 249.
Le Kuyameta, Vieill. Ois. Dor., tom. ii. p. 92. pl. 58.
Certhia Australasiæ, Leach, Zool. Misc., vol. i. pl. 11.
Meliphaga Cardinalis, Vig. and Horsf. in Linn. Trans., vol. xv. p.
316.
Blood-bird of the Colonists of New South Wales.

This beautiful little bird is an inhabitant of the thick brushes of


New South Wales, particularly those near the coast and those
clothing the hilly portions of the interior, and I have reason to believe
that it is rarely, if ever, found among the trees of the open parts of
the country. I have not yet seen specimens from the western, and
only a single example from the northern coasts, whence I infer that
the south-eastern part of the continent is its natural and restricted
habitat. It gives a decided preference to those parts of the forest that
abound with flowering plants, whose fragrant blossoms attract large
numbers of insects of various kinds, upon which and the pollen of
the flower-cups it chiefly subsists.
I regret to say that I was unable to obtain any information
respecting the nidification of this pretty species; but in this respect it
doubtless closely resembles the other members of the group.
The sexes are very dissimilar in colour, the female being of a
uniform pale brown above and lighter beneath, while the male is
dressed in a gorgeous livery of scarlet and black; the young, as is
usually the case where the sexes differ considerably in colour,
resembles the female until after the first moult, when it gradually
assumes the colouring of the male.
Much confusion exists in the writings of the older authors
respecting this bird, which has arisen from the circumstance of their
having considered it to be identical with two other species, one
inhabiting the Isle of Tanna, and the other the province of Bengal:
after a careful examination of the subject, I am of opinion that the
synonyms given above are all that have reference to the Australian
bird.
The male has the head, neck, breast, back and upper tail-coverts
rich shining scarlet; lores, wings and tail black, the wing-coverts
margined with huffy white, and the primaries with greyish olive;
under surface of the wing white; abdomen and under tail-coverts
buff; bill and feet black; irides dark brown.
The female is uniform light brown above, becoming much lighter
beneath.
The figures are those of the two sexes and of the natural size.
MYZOMELA
ERYTHROCEPHALA:
Gould.

J. Gould
and H. C.
Richter del
et lith.
C.
Hullmandel
Imp.
MYZOMELA ERYTHROCEPHALA, Gould.
Red-headed Honey-eater.

Myzomela erythrocephala, Gould in Proc. of Zool. Soc., Part VII.


p. 144.

The Red-headed Honey-eater is so distinctly marked as almost to


preclude the possibility of its being confounded with any known
species of the genus. In size it rather exceeds the common
Sanguineous Honey-eater, but is far more diminutive than the
species described by Latham as inhabiting the Isle of Tanna, under
the name of Certhia Cardinalis.
The northern portion of Australia would appear to be the true
habitat of the bird here represented, all the specimens that have
come under my notice having been procured at Port Essington,
where it is exclusively confined to the extensive beds of mangroves
bordering the inlets of the sea. From the flowers of these trees it
collects its favourite food, which, like that of the other species of the
group, consists of insects and honey. It is a most active little creature,
flitting from one cluster of flowers to another, and from branch to
branch with the greatest rapidity, uttering at the same time its rather
sharp and harsh chirrup. Mr. Gilbert states that it is far from being
abundant, and is so seldom seen near the settlement that no
examples had been procured prior to his visit.
The sexes present the usual difference in the smaller size and
sombre colouring of the female.
No information whatever was acquired respecting its nidification,
nor whether it be migratory or not.
The male has the head and rump scarlet, the remainder of the
plumage deep chocolate-brown; irides reddish brown; bill olive-
brown, becoming much lighter on the lower mandible; legs and feet
olive-grey.
The female is uniform brown above, lighter beneath.
The Plate represents two males and a female of the natural size.
MYZOMELA
PECTORALIS: Gould.

J. Gould
and H. C.
Richter del
et lith.
C.
Hullmandel
Imp.
MYZOMELA PECTORALIS, Gould.
Banded Honey-eater.

Myzomela pectoralis, Gould in Proc. of Zool. Soc., Part VIII. p.


170.

It will be seen from the number of novelties received from that


territory, that the northern coast of Australia possesses a fauna
almost peculiar to itself, few species, of the smaller birds at least,
being similar to those of the southern coast.
The present interesting bird was forwarded to me by Mr. Bynoe as
having been shot by him on the north coast, but I regret to say it was
unaccompanied by any information whatever respecting its habits.
In its structure it offers so close an alliance to the typical Myzomelæ
that I have provisionally placed it in that group.
Some of the specimens sent me had the centre of the back of a
ferruginous hue, while in others the same part was jet-black; I am
inclined to regard the former to be the plumage of the young birds of
the year, and it is just possible it may also be characteristic of the
adult female.
Forehead, crown of the head, upper surface, wings, tail and a
narrow band across the chest black; throat, upper tail-coverts and all
the under surface white; bill and feet black.
The birds are all figured of the natural size on one of the
interesting plants from the same locality.
MYZOMELA NIGRA;
(Gould).

Drawn
from
Nature &
on Stone by
J. & E.
Gould.
Printed by
C.
Hullmandel
.
MYZOMELA NIGRA, Gould.
Black Honey-eater.

Myzomela nigra, Gould in Birds of Australia, Part II. cancelled.


Dwer-da-ngok-ngun-nin, Aborigines of the mountain districts of
Western Australia.

This most active little bird is peculiar to the interior of Australia,


over which it has an extensive range. Mr. Gilbert found it in Western
Australia, and I myself met with it on the plains near the Namoi;
with me it was always on the Myalls (Acacia pendula),while in
Western Australia, where it is very local, it generally evinced a
preference for the sapling gums. Although it has the feathered tongue
and sometimes partakes of the sweets of the flowers, it feeds almost
exclusively on insects, which it procures both on the blossoms and
among the thickly-foliaged branches. The male possesses a feeble
plaintive note, which he frequently pours forth while perched upon
some elevated dead branch, where he sits with his neck stretching
out and without any apparent motion, except the swelling out of the
throat and the movement of the bill. Its flight is remarkably quick,
and performed with sudden zigzag starts.
The female differs remarkably from the male in the colouring of
the plumage, and, as is the case with many other birds, is much more
difficult of access than her mate, who is always more animated, and
frequently betrays his presence by his voice or song.
Mr. Gilbert was more fortunate than myself in finding the nest of
this little bird, and has furnished the following notes respecting its
incubation:—
“This species constructs a neat cup-shaped nest, formed of dried
grasses. I found two, both of which were built in the most
conspicuous situations; one in a fork at the top of a small scrubby
bush, unsheltered by even a bough or a leaf; the other was on the
dead branch of a fallen tree, in a similar exposed situation, and quite
unprotected from wet or heat. It breeds during the months of
October and November, and lays two eggs,” which are of a light
brownish buff, encircled at the centre with a band of brown,
produced by numerous small blotches of that colour, which appear
as if beneath the surface of the shell; they are seven lines long by five
and a half lines broad.
The male has the head, throat, stripe down the centre of the
abdomen, all the upper surface, wings and tail sooty black; the
remainder of the plumage pure white; irides blackish brown; bill and
feet black.
The female differs in having the head, all the upper surface, wings
and tail brown; throat and all the under surface brownish white, the
centre of each feather being the darkest; bill brown; legs brownish
black.
The Plate represents the two sexes of the natural size.
MYZOMELA
OBSCURA: Gould.

J. Gould
and H. C.
Richter del
et lith.
Hullmandel
& Walton
Imp.
MYZOMELA OBSCURA, Gould.
Obscure Honey-eater.

Myzomela obscura, Gould in Proc. of Zool. Soc., Part X. p. 136.

This species is a native of the northern parts of Australia. At Port


Essington, where my specimens were procured, it is only to be met
with in quiet, secluded and thickly-wooded districts adjacent to small
streams of water; its favourite tree appears to be the Grevillia, from
the blossoms of which it obtains great quantities of honey and
insects. The shy and retiring disposition of this species renders the
acquisition of specimens very difficult: “at no time during my stay,”
remarks Mr. Gilbert, “did I succeed in getting sight of more than a
solitary individual, and I believe it to be a rare bird in all parts of the
Cobourg Peninsula.”
This bird differs so much in colour from all the other species yet
discovered, that it is readily distinguished from all of them.
The sexes present no external marks of distinction, except that the
female is somewhat smaller than her mate.
The whole of the plumage is dull brown, with a vinous tinge on the
head; under surface paler than the upper; irides bright red; bill dark
greenish black; feet dark bluish grey; tarsi tinged with yellow.
The figures are of the natural size.
ENTOMYZA
CYANOTIS: Swains.

J. & E.
Gould del et
lith.
C.
Hullmandel
Imp.
ENTOMYZA CYANOTIS, Swains.
Blue-faced Entomyza.

Cracula cyanotis, Lath. Ind. Orn. Supp., p. xxix.—Shaw, Gen.


Zool., vol. vii. p. 474.
Blue-cheeked Honey-sucker, Meliphaga cyanops, Lewin, Birds of
New Holl., pl. 4.
Graculine Honey-eater, Lath. Gen. Hist., vol. iv. p. 166.
Blue-eared Grakle, Lath. Gen. Syn. Supp., vol. ii. p. 130.
Turdus cyaneus, Lath. Ind. Orn. Supp., p. xlii.
Blue-cheeked Thrush, Ib. Gen. Syn. Supp., vol. ii. p. 184.—Gen.
Hist., vol. v. p. 124.
Tropidorhynchus cyanotis, Vig. and Horsf. in Linn. Trans., vol.
xv. p. 325.
Entomyza cyanotis, Swains. Class. of Birds, vol. ii. p. 328.—G. R.
Gray, List of Gen. of Birds, p. 16.
L’Heorotaire graculé, Vieill. Ois. Dor., tom. ii. p. 125. pl. 87,
young.
Graculine Creeper, Shaw, Gen. Zool., vol. viii. p. 242, young.
Graculine Honey-eater, var. A., Lath. Gen. Hist., vol. iv. p. 166,
young.
Pale-cheeked Honey-eater, Ib., p. 167, young.
Merops cyanops, Lath. Ind. Orn. Supp., p. xxxiv, young.
Blue-cheeked Bee-eater, Ib. Gen. Syn. Supp., vol. ii. p. 154, young.
—Shaw, Gen. Zool., vol. viii. p. 171, young.
Blue-cheeked Honey-eater, Lath. Gen. Hist., vol. iv. p. 167,
young.
——, var. A. and B., Ib., p. 168, young.
White-crowned Honey-eater, Ib., p. 169, young.
Batikin, Aborigines of the coast of New South Wales.
Blue-eye of the Colonists.

This attractive and beautiful Honey-eater, one of the finest of the


Meliphagidæ, is strictly indigenous to New South Wales, where it is
abundant and very generally dispersed: I observed it in nearly every
part of the colony I visited, both in winter and summer. I also shot a
single specimen on the Namoi, but as this was almost the only one I
saw beyond the mountain ranges, I believe its most natural habitat to
be between the great dividing chain of mountains and the sea. In all
probability it may be found far to the northward on the eastern coast,
but it has not yet been observed in South Australia, neither is it an
inhabitant of Van Diemen’s Land.
In habits and actions the Blue-faced Honey-eater bears a striking
resemblance to the members of the genera Ptilotis and Hæmatops;
like them, it is found almost exclusively on the Eucalypti, searching
among the blossoms and smaller leafy branches for its food, which is
of a mixed character, consisting partly of insects and partly of honey,
and probably, judging from others of its family, berries and fruits,
but this latter supposition I was not able to verify. Mr. Caley states,
that he once saw “several of them frequenting a tree, where they were
very busy in obtaining something that appeared to have exuded from
a wounded part. I do not know what the substance could be,
otherwise than a kind of gum of a bitter and astringent taste.” As I
have never detected them in feeding on this or any similar substance,
I should rather suppose they were in search of the insects that might
have been attracted by this exudation.
I have frequently seen eight or ten of these bold and spirited birds,
with numerous other small Honey-eaters and Parrakeets, on a single
tree, displaying the most elegant and easy movements, clinging and
hanging in every variety of position, frequently at the extreme ends
of the small, thickly-flowered branches, bending them down with
their weight; they may, however, be easily distinguished from the
other birds with which they are in company by their superior size,
the brilliancy of their blue face, and the contrasted colours of their
plumage; they are rendered equally conspicuous by the pugnacity
with which they chase and drive about the other species resorting to
the same tree.
It frequently utters a rather loud and monotonous cry, not worthy
the name of a song.
I observed a most curious fact respecting the nidification of this
bird: in every instance that I found its eggs, they were deposited on
the deserted, dome-shaped, large nest of the Pomatorhinus, so
numerous in the Apple-tree Flats in the district of the Upper Hunter;
never within the dome, but in a neat round depression on the top. I
had many opportunities of driving the female off the nest, and I can
therefore speak with confidence as to this fact. Whether this bird
resorts only to places where it may avail itself of the nest of the
Pomatorhinus, or whether, under other circumstances, it constructs
a nest for itself, are points to which I would call the attention of those
who are favourably situated for investigating them; and who, by so
doing, would render the history of this species so much the more
complete. It is probable that, in places where no suitable substitute is
to be found, it makes a rather small nest, like all the other species of
its tribe. It commences breeding early, and rears at least two broods
in the year: on reference to my note-book, I find I saw fully-fledged
young on the 19th of November, and that I took many of their eggs in
December: they were generally two in number, of a rich salmon
colour irregularly spotted with rust-brown, one inch and a quarter
long by ten and a half lines broad.
The sexes differ in no respect from each other either in the
colouring of the plumage or in the blended richness and delicacy of
the blue surrounding the eye, to which it is almost impossible for the
artist to do justice.
The young assume the plumage of the adult from the nest, but
differ from them in having the naked face and the base of the bill of a
pale yellowish olive, which gradually changes to blue after the first
season; this has doubtless occasioned the great number of synonyms
quoted above.
The adults have the crown of the head and back of the neck black;
lower part of the face, chin and centre of the chest slaty black; a
crescent-shaped mark at the occiput, a line from the lower mandible
passing down each side of the neck, and all the under surface pure
white; the upper surface, wings, and tail golden olive; the inner webs
of the primaries and all but the two centre tail-feathers brown; the
tail-feathers tipped with white; basal portion of the bill pale bluish
grey, passing into blackish horn-colour at the tip; bare space
surrounding the eye rich deep blue, becoming of a lighter and
greenish hue above the eye; irides yellowish white; eyelash jet-black;
feet bluish grey.
The young of the first autumn have the eye dark olive with a black
lash, and the denuded parts surrounding it, the base of the under
mandible and the gape greenish brimstone-yellow; nostrils and
culmen near the head yellowish horn-colour, passing into blackish
brown at the tip; feet very similar to those of the adult.
The Plate represents a male and female of the natural size, on a
branch of one of the lofty Eucalypti of the river Hunter.
ENTOMYZA
ALBIPENNIS: Gould.

J. Gould
and H. C.
Richter del
et lith.
C.
Hullmandel
Imp.
ENTOMYZA ALBIPENNIS, Gould.
White-pinioned Honey-eater.

Entomyza albipennis, Gould in Proc. of Zool. Soc., Part VIII. p.


169.
Wȕr-ra-luh, Aborigines of Port Essington.

The Entomyza albipennis exhibits so many specific differences


from the E. cyanotis, that it is almost impossible for one to be
mistaken for the other: in the first place it is somewhat smaller in
size, and in the next the tints of the plumage are more strongly
contrasted; besides which, the white at the basal portion of the
pinions is a character which will at all times distinguish it from its
near ally. So far as is yet known, its habitat is confined to the
northern coast of Australia, where it is said to be rather abundant,
particularly in the neighbourhood of the settlement at Port Essington
on the Cobourg Peninsula. Mr. Gilbert states that it “is very shy, and
from its being always on the alert, somewhat difficult to get near; it is
one of the first birds heard in the morning, and often utters its
plaintive peet half-an-hour before daylight; as soon as the sun is
fairly above the horizon, its note is immediately changed to a harsh
squeaking tone, which is frequently uttered while the bird is on the
wing, and repeated at intervals throughout the day; it often takes
tolerably long flights, mounting in the air to a considerable height
above the trees, and then progressing steadily and horizontally. It is
mostly met with in small families of from six to ten in number,
inhabiting the topmost branches of the loftiest trees, and is seldom
seen on or near the ground.”
The food consists of insects and the pollen of flowers, which are
procured from the almost perpetually flowering Eucalypti.
The sexes present little or no difference in the colouring of the
plumage, or, when fully adult, in the colouring of the soft parts, such
as the naked skin round the eyes, Sec.; immature birds, on the
contrary, vary very much in the colouring of the face and bill; in the
youthful those parts are saffron-yellow, which chances to rich
ultramarine blue in the adult.
The adults have the crown of the head and back of the neck black;
lower part of the face, chin and centre of the chest slaty black; a
crescent-shaped mark at the occiput, a line from the lower mandible
passing down each side of the neck, and all the under surface pure
white; upper surface and wings greenish golden olive; primaries
brown, the basal half of their inner webs snow-white; tail-feathers
brown, tinged with golden olive, all but the two centre ones tipped
with white; point and cutting edges of the upper mandible blackish
grey; basal half of the culmen horn-colour; remainder of the bill
sulphur-yellow; orbits brilliant blue; legs and feet leek-green.
The Plate represents an adult and an immature bird of the natural
size.
MELITHREPTUS
VALIDIROSTRUS:
Gould.

J. Gould
and H. C.
Richter del
et lith.
Hullmandel
& Walton
Imp.
MELITHREPTUS VALIDIROSTRIS, Gould.
Strong-billed Honey-eater.

Hæmatops validirostris, Gould in Proc. of Zool. Soc., Part IV. p.


144; and in Syn. Birds of Australia, Part I.
Eidopsaris bicinctus, Swains. An. in Menag., p. 344. No. 188.—Ib.
Class. of Birds, vol. ii. p. 327.
Cherry-picker, Colonists of Van Diemen’s Land.

This bird, the largest species of the genus yet discovered, is a


native of Van Diemen’s Land, and so universally is it distributed over
that island, that scarcely any part is without its presence. The crowns
of the highest mountains as well as the lowlands, if clothed with
Eucalypti, are equally enlivened by it. Like all the other members of
the genus, it frequents the small leafy and flowering branches; it
differs, however, from its congeners in one remarkable character,
that of alighting upon and clinging to the surface of the boles of the
trees in search of insects, after the manner of the Woodpecker and
Nuthatch,—not that it can traverse this part of the tree with the same
facility; I never in fact saw it run up and down the trunk as those
birds do, but merely fly to such parts as instinct led it to select as the
probable abode of insects; and it always perches across the stem,—a
position seldom, if ever, assumed by the Nuthatch or Woodpecker; I
do not, however, consider this habit of sufficient importance to
warrant its separation from those with which it is here associated.
The chief food of this species is insects of various kinds, after
which it searches with the most scrutinizing care among the
flowering gums.
I am indebted to my friend the Rev. Thomas J. Ewing of Hobart
Town, Van Diemen’s Land, for the nest and eggs of this bird, which I
failed in procuring during my stay in that island. Like those of the
other members of the genus the nest is round and cup-shaped,
suspended by the rim and formed of coarse wiry grasses, with a few
blossoms of grasses for a lining; the eggs are three in number, eleven
lines long by eight lines broad, and of a dull olive-buff, thickly
spotted and blotched with markings of purplish brown and bluish
grey, the latter appearing as if beneath the surface of the shell.
The sexes assimilate so closely in size and plumage, that by
dissection alone can they be distinguished; the young, on the
contrary, during the first autumn differ so considerably from the
adult, as almost to induce the belief that they are the young of some
other species; having, however, killed them myself at the breeding-
place in company with the adults, I can vouch that they are really the
young of this bird and of none other. The specimens from which the
upper figures in the accompanying Plate were taken, were shot by
myself near the summit of Mount Wellington. I may mention that in
the vast forests of gums on the banks of the Tamar, this species was
equally or even more abundant than in the southern part of the
island. I have never seen it on the continent of Australia, neither
have specimens been sent from New South Wales or South Australia.
Its song consists of a couple of notes and is not remarkable for its
melody.
Crown of the head jet-black, with an occipital band of white
terminating at each eve; ear-coverts, chin and back of the neck black;
all the upper surface greyish olive, becoming brighter on the rump
and external edges of the tail-feathers; wings brown, with a slight
tinge of olive; throat pure white; under surface brownish grey; bill
black; feet brownish horn-colour; eyes reddish brown; bare skin over
the eye white, tinged with bright green.
The young have the bill and feet yellow, but the latter paler than
the former, and a circle of the same colour round the eye; the band at
the occiput is also pale yellow instead of white.
The Plate represents an adult male and two young birds in the
plumage of the first autumn, of the natural size.

You might also like