liveBook · Manning

Keyword

As explained in The Well-Grounded Rubyist, Fourth Edition

A Ruby keyword is a predefined reserved term associated with a specific programming construct or syntactic context, including the logical-negation keyword not.

Consider `def obj.talk`. Ruby recognizes `def` as a keyword that starts a method definition. `obj` and `talk` play different roles: one identifies the object, and the other names the method being defined. A keyword is a reserved word with a designated syntactic role, not a variable name. section 2.1.2 section 2.5.4

When Ruby encounters a bare word, it first checks whether the word is a keyword. Otherwise, `=` can mark a local-variable assignment, and following parentheses identify a method call. Without either clue, Ruby tries to resolve the word as a local variable or method call. An unresolved `x` therefore produces an error naming both possibilities. section 2.5.4

Keywords appear in several kinds of construct:

$ ruby -e "x"
-e:1:in `<main>': undefined local variable or method 'x'
➥for main:Object (NameError))

The error for bare `x` illustrates why distinguishing keywords from local variables and method calls matters. section 2.5.4

How The Well-Grounded Rubyist, Fourth Edition covers it

How deep it goes
Explains reserved words and the order of bareword resolution, without cataloging every keyword.
Examples
Uses `def`, `if`, `class`, `true`, `false`, and an unresolved bare `x` to distinguish syntactic roles.
What it assumes
Builds identifier recognition from basic variable forms, then draws on local variables and method calls.
What you can do after
Diagnose/debug ambiguous Ruby barewords by checking for a keyword, assignment, parentheses, or an existing definition.
How it connects
Connects keywords to local variables, method calls, method definitions, class definitions, conditionals, and Boolean objects.

Also explained in

Compare how 3 books explain keyword →

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.