liveBook · Manning

Bareword invocation

As explained in The Well-Grounded Rubyist, Fourth Edition

Bareword style is invoking a Ruby method without writing an explicit receiver.

A bareword invocation calls a Ruby method without an explicit receiver or dot. In `puts "Hello"`, Ruby sends the `puts` message to the current object, `self`. Because some method calls omit visible message-sending syntax, recognizing the implicit receiver is essential to reading Ruby code. section 1.1.4 section 1.5

A bareword call and its explicit counterpart

`puts "Hello"` uses bareword style; `self.puts "Hello"` makes the receiver explicit. The two forms express the same target here: the object currently bound to `self`. Which object that is depends on Ruby's execution context. section 1.1.4

Top-level methods clarify why this syntax works. A method defined at the top level becomes a private instance method of `Object`, so it can be called without a receiver—or with `self`—but not with an unrelated explicit receiver. Since `Object` lies in the lookup path of nearly every object, such methods support script-friendly procedural commands. section 5.4.1 section 5.4.1

def talk
  puts "Hello"
end
puts "Trying 'talk' with no receiver..."
talk                  1
puts "Trying 'talk' with an explicit receiver..."
obj = Object.new
obj.talk                 2

Compare a top-level method called bareword-style with the failure produced by an unrelated explicit receiver. section 5.4.1

How The Well-Grounded Rubyist, Fourth Edition covers it

How deep it goes
Explains the implicit self receiver and top-level method visibility, while deferring a fuller treatment of self.
Examples
Uses `puts "Hello"`, a top-level `talk` method, and an `Object.new` call with an explicit receiver.
What it assumes
Assumes basic Ruby expressions and methods while introducing objects, messages, receivers, and self through small examples.
What you can do after
Apply bareword calls in irb and Ruby scripts, and diagnose failures caused by explicit receivers on private methods.
How it connects
Connects bareword invocation to Ruby objects, self, private methods, Object, message sending, and method lookup.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Well-Grounded Rubyist, Fourth Edition. The section links point to the parts of the book it draws on.