Topics A–Z¶
Level: reference · for anyone looking for a page by the name they know it by
Every lesson, listed under its title, its folder name and the words a reader might search for. The arrow reads this name → the page that covers it; the dash gives the page's claim. Generated from the lessons' own titles and one-line claims — see the crosswalk for the same pages arranged by idea beside their Python spellings.
¶
#{}callsto_s;formatis printf —"#{expr}"evaluates any expression and callsto_son the result&.skips the call when the receiver is nil —receiver&.method(args)returnsnilwithout calling anything&:symcallsSymbol#to_proc—&xin an argument list callsx.to_procand attaches the result as the block; a symbol'sto_procis a lambda…0.1 + 0.2 != 0.3, and2.5.roundis3— A Ruby Float is the same 64-bit double as a Python float1 + 1.5works because Integer asks Float tocoerce— WhenInteger#+meets an operand it does not know, it calls that object'scoerceand adds the pair it gets back1 == 1.0is true, but{1 => :a}[1.0]isnil— Ruby's==compares an Integer with a Float by value1/3randBigDecimal("0.1")are exact where Float is not — Ruby ships two exact number types beside Float- 503 → A
SizedQueuethat refuses is the 503 behind "queue full" — Passenger answers a Rails app's requests from a fixed pool of processes, 6 by default, through a request queue with a… - 504 → A
SizedQueuethat refuses is the 503 behind "queue full" — Passenger answers a Rails app's requests from a fixed pool of processes, 6 by default, through a request queue with a… 7 / 2is3: integer division floors — Ruby's/on two Integers is Python's//
A¶
- A backtrace is data you can read —
callerreturns an Array of Strings shapedfile:line:in 'Klass#method',caller_locationsreturns the same… - A bare
rescuecatchesStandardError, not everything —rescuewith no class list meansrescue StandardError, andSystemExit,Interrupt,NoMemoryError,… - A Binding is a scope you can carry around —
bindingpackages a method's local variables, itsselfand its name into an object thateval,ERB#resultand… - A DSL is
instance_evalplus stored blocks — A Ruby DSL is ordinary method calls made readable by three tricks - A Fiber is a coroutine you resume by hand —
Fiber.new { }makes a block that runs only when youresumeit and stops wherever it callsFiber.yield; values… - A Hash key needs
eql?andhash, not==— AHashfinds a key by callinghashand theneql? - A method is a value once you ask for it —
obj.method(:name)hands back aMethodbound toobj, andKlass.instance_method(:name)anUnboundMethodyou… - A Minitest test is a plain class — Minitest, a bundled gem, runs every
test_*method of aMinitest::Testsubclass in a seeded random order and… - A missing key is nil, and
Hash.new([])shares its default —h[:zz]isnilwhered["zz"]raisesKeyError;fetchis the raising form;Hash.new(0)returns a default… - A module is a namespace, and cannot be instantiated —
module Shopis a named box for classes, constants and methods - A pin compares; a bare name binds — Inside a pattern a bare name always binds
- A setter returns its argument, not its body —
obj.x = 5is a call to the methodx=, but as an expression it evaluates to 5 whatever the method body returns - a sized queue that refuses → A
SizedQueuethat refuses is the 503 behind "queue full" — Passenger answers a Rails app's requests from a fixed pool of processes, 6 by default, through a request queue with a… - A
SizedQueuethat refuses is the 503 behind "queue full" — Passenger answers a Rails app's requests from a fixed pool of processes, 6 by default, through a request queue with a… - A string key and a symbol key are two keys —
{"a" => 1}[:a]isnilbecause"a"and:aare different objects of different classes,JSON.parsealways… - A symbol is a name, not a string — A Ruby symbol is an immutable name of which exactly one object exists per spelling
- A variable is a reference, not a box — Assignment copies a reference, never the object, so after
b = aa mutating method such as<<onbis seen… - added → Hooks fire when code is defined, not when it runs —
inherited,included,extended,prepended,method_added,singleton_method_addedandconst_addedare… - allocate →
newisallocatetheninitialize—Point.new(1, 2)is a class method that does two things - alternatives → A pin compares; a bare name binds — Inside a pattern a bare name always binds
- An Enumerator has a cursor:
next,peek,rewind— Anyeachcalled without a block returns anEnumerator;nextpulls one value from it,peeklooks at the next… - An iterator is a method that yields — A class earns the whole
Enumerabletoolbox by writing oneeachthat yields and including the module; `return… - An object can list its methods and variables —
methods,instance_methods(false),instance_variables,instance_method(:x).parameters,source_location,… - and or precedence →
and/orbind lower than=— Ruby has two pairs of boolean operators and/orbind lower than=— Ruby has two pairs of boolean operators- argf →
getsreturns nil at EOF, and readsARGV's files first —getsreturns the next line with its newline andnilat end of input - argument → A setter returns its argument, not its body —
obj.x = 5is a call to the methodx=, but as an expression it evaluates to 5 whatever the method body returns - arguments → Arguments: positional, keyword, splat and block — A Ruby parameter list has eight kinds of slot
- arguments → Default arguments are evaluated on every call — A Ruby default is an expression that runs each time the method is called without that argument, so
def f(a = [])… - arguments positional keyword and splat → Arguments: positional, keyword, splat and block — A Ruby parameter list has eight kinds of slot
- Arguments: positional, keyword, splat and block — A Ruby parameter list has eight kinds of slot
- argv →
ARGVholds strings andENVis not a Hash —ARGVis an Array of Strings,$0is the script name as it was invoked,ENVis a Hash-like object whose values… - argv env and exit status →
ARGVholds strings andENVis not a Hash —ARGVis an Array of Strings,$0is the script name as it was invoked,ENVis a Hash-like object whose values… ARGVholds strings andENVis not a Hash —ARGVis an Array of Strings,$0is the script name as it was invoked,ENVis a Hash-like object whose values…- arrays → Past the end, an array gives nil, not an error —
a[10]on a four-element array isnil,a[5] = 99pads the gap withnil, and a slice isa[1..2](end… - arrays and negative indexes → Past the end, an array gives nil, not an error —
a[10]on a four-element array isnil,a[5] = 99pads the gap withnil, and a slice isa[1..2](end… - assignment → Assignment destructures, and blocks auto-splat —
a, b = 1, 2,a, *rest = listand(a, b), c = pair, 3read like Python - Assignment destructures, and blocks auto-splat —
a, b = 1, 2,a, *rest = listand(a, b), c = pair, 3read like Python
B¶
- backpressure → A
SizedQueuethat refuses is the 503 behind "queue full" — Passenger answers a Rails app's requests from a fixed pool of processes, 6 by default, through a request queue with a… - backtraces → A backtrace is data you can read —
callerreturns an Array of Strings shapedfile:line:in 'Klass#method',caller_locationsreturns the same… - backtraces and caller → A backtrace is data you can read —
callerreturns an Array of Strings shapedfile:line:in 'Klass#method',caller_locationsreturns the same… - bang → Bang means dangerous, question mark means predicate — A trailing
!marks the more dangerous of two versions of a method - bang and question methods → Bang means dangerous, question mark means predicate — A trailing
!marks the more dangerous of two versions of a method - Bang means dangerous, question mark means predicate — A trailing
!marks the more dangerous of two versions of a method - basic →
Objectsits onKernelonBasicObject—Object.ancestorsis[Object, Kernel, BasicObject]andObjectitself defines no public methods - basic object and kernel →
Objectsits onKernelonBasicObject—Object.ancestorsis[Object, Kernel, BasicObject]andObjectitself defines no public methods - bigdecimal →
1/3randBigDecimal("0.1")are exact where Float is not — Ruby ships two exact number types beside Float - binding → A Binding is a scope you can carry around —
bindingpackages a method's local variables, itsselfand its name into an object thateval,ERB#resultand… - binding and eval → A Binding is a scope you can carry around —
bindingpackages a method's local variables, itsselfand its name into an object thateval,ERB#resultand… - block →
File.openwith a block closes the file for you —File.open(name, mode) { |f| … }closes the file when the block ends and evaluates to the block's value; Python's… - blocks → Blocks are not objects — A block is syntax attached to one method call
- blocks →
next,breakandreturnleave a block differently —next vends this run of the block withvas its value,break vends the method the block was given to and… - blocks are not objects → Blocks are not objects — A block is syntax attached to one method call
- break →
next,breakandreturnleave a block differently —next vends this run of the block withvas its value,break vends the method the block was given to and… - building → A DSL is
instance_evalplus stored blocks — A Ruby DSL is ordinary method calls made readable by three tricks - building a dsl → A DSL is
instance_evalplus stored blocks — A Ruby DSL is ordinary method calls made readable by three tricks - bundler → Gems are versioned; Bundler pins them — A gem is a versioned package that RubyGems can activate by name (
gem "x"), some ship inside Ruby (default gems),… - bytecode → Ruby shows you its bytecode and its syntax tree —
RubyVM::InstructionSequence.compile(src).disasmlists the YARV instructions the interpreter will execute and…
C¶
- call → Default arguments are evaluated on every call — A Ruby default is an expression that runs each time the method is called without that argument, so
def f(a = [])… - caller → A backtrace is data you can read —
callerreturns an Array of Strings shapedfile:line:in 'Klass#method',caller_locationsreturns the same… - capture → Closures capture variables, not values — A block, proc or lambda carries the variables around it
- case →
case/inmatches shape, not just value —case … intests a value against a pattern - case →
case/whenasks===, and every class answers it its own way —case x when ycallsy === x, and===is an ordinary method: a class answers withis_a?, a Range with… - case in pattern matching →
case/inmatches shape, not just value —case … intests a value against a pattern - case when uses threequals →
case/whenasks===, and every class answers it its own way —case x when ycallsy === x, and===is an ordinary method: a class answers withis_a?, a Range with… case/inmatches shape, not just value —case … intests a value against a patterncase/whenasks===, and every class answers it its own way —case x when ycallsy === x, and===is an ordinary method: a class answers withis_a?, a Range with…- catch →
throwandcatchare not exceptions —catch(:tag) { … throw :tag, value … }is a labelled non-local jump:throwunwinds to the matchingcatch, which… - cause → Exceptions have a
cause— Araisethat runs while arescueclause is handling another exception records that exception as the new one's… - chaining →
tapreturns the receiver,thenreturns the block's value —x.tap { … }yieldsxto the block and returnsxwhatever the block returned, so a debuggingputscan sit… - changed → What changed, 1.9 to 4.0 — Ruby's releases each added a few things you will meet in old code and new
- class → Class variables are shared with subclasses —
@@countis one variable, owned by the class that first assigns it and seen by every subclass and every instance - class → Set is a core class in 4.0 and keeps insertion order — In Ruby 4.0
Setneeds norequireand is written in C,Set[3, 1, 2]iterates as 3, 1, 2, and an element is… - class →
instance_evalmovesself,class_evalmovesdef— Both evals run a block withselfset to the receiver; the difference is where adefinside lands - class variables are shared → Class variables are shared with subclasses —
@@countis one variable, owned by the class that first assigns it and seen by every subclass and every instance - Class variables are shared with subclasses —
@@countis one variable, owned by the class that first assigns it and seen by every subclass and every instance Class.newmakes a class; a constant names it —Class.new(Base) { ... }returns a class object with no name,Foo = klassgives it the name of the first constant…- classes → Classes are open —
class Stringwritten a second time does not make a new class - classes → Custom exceptions subclass
StandardError— Inherit fromStandardError(neverException), giveinitializea default message and pass it tosuper, add… - classes → Every object has a class of its own — A method defined on one object
- classes →
Class.newmakes a class; a constant names it —Class.new(Base) { ... }returns a class object with no name,Foo = klassgives it the name of the first constant… - Classes are open —
class Stringwritten a second time does not make a new class - classes at runtime →
Class.newmakes a class; a constant names it —Class.new(Base) { ... }returns a class object with no name,Foo = klassgives it the name of the first constant… - clone →
dupis a fresh copy,cloneis a faithful one —dupandcloneboth make a new object with the same instance variables, and both are shallow - closures → Closures capture variables, not values — A block, proc or lambda carries the variables around it
- closures capture variables → Closures capture variables, not values — A block, proc or lambda carries the variables around it
- Closures capture variables, not values — A block, proc or lambda carries the variables around it
- coercion →
1 + 1.5works because Integer asks Float tocoerce— WhenInteger#+meets an operand it does not know, it calls that object'scoerceand adds the pair it gets back - command → The command line is part of the language —
rubytakes flags for running code (-e), checking it (-c), warning about it (-w,-W:category), loading… - comments → Ruby has block comments and a data section — Ruby comments with
#, with=begin/=endblocks that must start at column 0, and with magic comments the parser… - comments and documentation → Ruby has block comments and a data section — Ruby comments with
#, with=begin/=endblocks that must start at column 0, and with magic comments the parser… - common → Common error messages — Twenty-nine errors you will meet in your first month of Ruby, each with the code that raises it, the message Ruby…
- Common error messages — Twenty-nine errors you will meet in your first month of Ruby, each with the code that raises it, the message Ruby…
- comparable → Define
<=>and Comparable gives you the rest —<=>answers-1,0,1ornil("these do not compare");include Comparableturns that one method into<,… - comparable and spaceship → Define
<=>and Comparable gives you the rest —<=>answers-1,0,1ornil("these do not compare");include Comparableturns that one method into<,… - comparing →
1 == 1.0is true, but{1 => :a}[1.0]isnil— Ruby's==compares an Integer with a Float by value - comparing int and float →
1 == 1.0is true, but{1 => :a}[1.0]isnil— Ruby's==compares an Integer with a Float by value - composition → Procs curry and compose —
Proc#curryturns an n-argument lambda into a chain of one-argument lambdas,>>and<<compose any two… - condition → Mutex guards, Queue hands over, ConditionVariable waits —
Mutex#synchronizemakescount += 1exact across ten threads, aQueuemoves work from one thread to another and… - constants → Constants are found lexically, then through ancestors — A bare constant name is resolved by the lexical nesting the code was written in (
Module.nesting), then through the… - constants and lexical scope → Constants are found lexically, then through ancestors — A bare constant name is resolved by the lexical nesting the code was written in (
Module.nesting), then through the… - Constants are found lexically, then through ancestors — A bare constant name is resolved by the lexical nesting the code was written in (
Module.nesting), then through the… - core → Set is a core class in 4.0 and keeps insertion order — In Ruby 4.0
Setneeds norequireand is written in C,Set[3, 1, 2]iterates as 3, 1, 2, and an element is… - coroutines → A Fiber is a coroutine you resume by hand —
Fiber.new { }makes a block that runs only when youresumeit and stops wherever it callsFiber.yield; values… - curry → Procs curry and compose —
Proc#curryturns an n-argument lambda into a chain of one-argument lambdas,>>and<<compose any two… - curry and composition → Procs curry and compose —
Proc#curryturns an n-argument lambda into a chain of one-argument lambdas,>>and<<compose any two… - custom → Custom exceptions subclass
StandardError— Inherit fromStandardError(neverException), giveinitializea default message and pass it tosuper, add… - custom exception classes → Custom exceptions subclass
StandardError— Inherit fromStandardError(neverException), giveinitializea default message and pass it tosuper, add… - Custom exceptions subclass
StandardError— Inherit fromStandardError(neverException), giveinitializea default message and pass it tosuper, add…
D¶
- dash → Warnings go to stderr, and
-wfinds more of them —warnprints to stderr;-wsets$VERBOSEtotrueand makes Ruby report unused variables, redefined methods,… - data → Struct is mutable, Data is not —
Struct.new(:x, :y)makes a record you can build positionally or by keyword and then change; `Data.define(:lat,… - date →
Timeis an instant,Dateis a calendar day — aTimeis a point on the timeline with an offset attached - deconstruct →
deconstructanddeconstruct_keyslet any object be matched — An array pattern calls the subject'sdeconstructand a hash pattern callsdeconstruct_keys(keys) - deconstruct and deconstruct keys →
deconstructanddeconstruct_keyslet any object be matched — An array pattern calls the subject'sdeconstructand a hash pattern callsdeconstruct_keys(keys) deconstructanddeconstruct_keyslet any object be matched — An array pattern calls the subject'sdeconstructand a hash pattern callsdeconstruct_keys(keys)- default → A bare
rescuecatchesStandardError, not everything —rescuewith no class list meansrescue StandardError, andSystemExit,Interrupt,NoMemoryError,… - default → A missing key is nil, and
Hash.new([])shares its default —h[:zz]isnilwhered["zz"]raisesKeyError;fetchis the raising form;Hash.new(0)returns a default… - default → Default arguments are evaluated on every call — A Ruby default is an expression that runs each time the method is called without that argument, so
def f(a = [])… - default arguments are evaluated each call → Default arguments are evaluated on every call — A Ruby default is an expression that runs each time the method is called without that argument, so
def f(a = [])… - Default arguments are evaluated on every call — A Ruby default is an expression that runs each time the method is called without that argument, so
def f(a = [])… - define →
define_methodturns a block into a method —define_method(:name) { ... }installs a method whose body is a closure - Define
<=>and Comparable gives you the rest —<=>answers-1,0,1ornil("these do not compare");include Comparableturns that one method into<,… - define method →
define_methodturns a block into a method —define_method(:name) { ... }installs a method whose body is a closure define_methodturns a block into a method —define_method(:name) { ... }installs a method whose body is a closure- destructuring → Assignment destructures, and blocks auto-splat —
a, b = 1, 2,a, *rest = listand(a, b), c = pair, 3read like Python - destructuring assignment → Assignment destructures, and blocks auto-splat —
a, b = 1, 2,a, *rest = listand(a, b), c = pair, 3read like Python - differ → Procs and lambdas differ in arity and
return— Every proc and lambda is aProc, but a lambda checks its argument count andreturns from itself, while a proc… - dir →
Pathname#/joins, andDir.globis sorted —Pathnameis an object with/,basename,extname,parent,children,exist?andread;Dir.glob… - division →
7 / 2is3: integer division floors — Ruby's/on two Integers is Python's// - docstrings → Ruby has no docstrings — A Ruby method carries no documentation at run time
- documentation → Ruby has block comments and a data section — Ruby comments with
#, with=begin/=endblocks that must start at column 0, and with magic comments the parser… - dots → Two dots include the end, three dots exclude it —
1..5is five numbers and1...5is four; a Range can be endless (1..), beginless (..5), made of Strings… - dsl → A DSL is
instance_evalplus stored blocks — A Ruby DSL is ordinary method calls made readable by three tricks - duck → Duck typing asks
respond_to?, notclass— Ruby code asks an object what it can do - duck typing and respond to → Duck typing asks
respond_to?, notclass— Ruby code asks an object what it can do - Duck typing asks
respond_to?, notclass— Ruby code asks an object what it can do - dup →
dupis a fresh copy,cloneis a faithful one —dupandcloneboth make a new object with the same instance variables, and both are shallow - dup clone and frozen state →
dupis a fresh copy,cloneis a faithful one —dupandcloneboth make a new object with the same instance variables, and both are shallow dupis a fresh copy,cloneis a faithful one —dupandcloneboth make a new object with the same instance variables, and both are shallow
E¶
- else →
rescue,elseandensurerun in a fixed order — The body runs first; thenrescueif it raised orelseif it did not; thenensure, always - ensure →
rescue,elseandensurerun in a fixed order — The body runs first; thenrescueif it raised orelseif it did not; thenensure, always - enumerable → Enumerable is a mixin: write
each, get the rest — A class that defineseachand saysinclude Enumerablegainsmap,select,sort_by,min_by,include?,… - enumerable → Most loops you would write are one Enumerable call —
map,select,reject,find,partition,group_by,tally,each_slice,each_cons,zip,flat_map,… - enumerable is a mixin → Enumerable is a mixin: write
each, get the rest — A class that defineseachand saysinclude Enumerablegainsmap,select,sort_by,min_by,include?,… - Enumerable is a mixin: write
each, get the rest — A class that defineseachand saysinclude Enumerablegainsmap,select,sort_by,min_by,include?,… Enumerator#nextruns the block on its own Fiber —each,to_a,mapandfirstrun anEnumerator's block where they are called, on the calling fiber;next…- enumerators → An Enumerator has a cursor:
next,peek,rewind— Anyeachcalled without a block returns anEnumerator;nextpulls one value from it,peeklooks at the next… - enumerators →
Enumerator#nextruns the block on its own Fiber —each,to_a,mapandfirstrun anEnumerator's block where they are called, on the calling fiber;next… - enumerators →
lazyruns the chain one element at a time —mapandselecton an ordinary collection each run to the end and build an array before the next stage starts;… - enumerators run on fibers →
Enumerator#nextruns the block on its own Fiber —each,to_a,mapandfirstrun anEnumerator's block where they are called, on the calling fiber;next… - env →
ARGVholds strings andENVis not a Hash —ARGVis an Array of Strings,$0is the script name as it was invoked,ENVis a Hash-like object whose values… - eql → A Hash key needs
eql?andhash, not==— AHashfinds a key by callinghashand theneql? - eql and hash for hash keys → A Hash key needs
eql?andhash, not==— AHashfinds a key by callinghashand theneql? - equality → Ruby has four kinds of equality —
equal?is identity,==is value,eql?is value without type conversion (the testHashkeys use), and===… - equals →
x ||= vassigns whenxis nil or false —x ||= visx || (x = v): it assigns whenxisnilorfalseand leaves every other value alone, so it… - error → A bare
rescuecatchesStandardError, not everything —rescuewith no class list meansrescue StandardError, andSystemExit,Interrupt,NoMemoryError,… - error → Common error messages — Twenty-nine errors you will meet in your first month of Ruby, each with the code that raises it, the message Ruby…
- error → Nothing matched:
case/inraises,case/whenreturnsnil— Acase/inwith no matching branch and noelse, and a rightwardvalue => pattern, raiseNoMatchingPatternError - error →
freezeis shallow and raisesFrozenError—freezemakes one object immutable - eval → A Binding is a scope you can carry around —
bindingpackages a method's local variables, itsselfand its name into an object thateval,ERB#resultand… - eval →
instance_evalmovesself,class_evalmovesdef— Both evals run a block withselfset to the receiver; the difference is where adefinside lands - evaluated → Default arguments are evaluated on every call — A Ruby default is an expression that runs each time the method is called without that argument, so
def f(a = [])… - Every object has a class of its own — A method defined on one object
- everything → Everything is an expression, even
defandclass— Every Ruby construct - everything → Everything is an object, even
1andnil— Every Ruby value - everything is an expression → Everything is an expression, even
defandclass— Every Ruby construct - Everything is an expression, even
defandclass— Every Ruby construct - everything is an object → Everything is an object, even
1andnil— Every Ruby value - Everything is an object, even
1andnil— Every Ruby value - exception → Custom exceptions subclass
StandardError— Inherit fromStandardError(neverException), giveinitializea default message and pass it tosuper, add… - exceptions → Exceptions have a
cause— Araisethat runs while arescueclause is handling another exception records that exception as the new one's… - Exceptions have a
cause— Araisethat runs while arescueclause is handling another exception records that exception as the new one's… - exceptions have a cause → Exceptions have a
cause— Araisethat runs while arescueclause is handling another exception records that exception as the new one's… - exit →
ARGVholds strings andENVis not a Hash —ARGVis an Array of Strings,$0is the script name as it was invoked,ENVis a Hash-like object whose values… - exit →
exitraisesSystemExit—exitis not a system call but araiseofSystemExit, soensureclauses andat_exithandlers run, a `rescue… - exit at exit and system exit →
exitraisesSystemExit—exitis not a system call but araiseofSystemExit, soensureclauses andat_exithandlers run, a `rescue… exitraisesSystemExit—exitis not a system call but araiseofSystemExit, soensureclauses andat_exithandlers run, a `rescue…- expression → Everything is an expression, even
defandclass— Every Ruby construct - expression → The last expression is the return value — A Ruby method returns the value of the last expression it evaluated, so
returnis only for leaving early - extend → Mixins:
include,extend,prepend—includeinserts a module into the class's ancestor chain behind the class,prependinserts it in front so… - external → An Enumerator has a cursor:
next,peek,rewind— Anyeachcalled without a block returns anEnumerator;nextpulls one value from it,peeklooks at the next… - external enumerators → An Enumerator has a cursor:
next,peek,rewind— Anyeachcalled without a block returns anEnumerator;nextpulls one value from it,peeklooks at the next…
F¶
- false → Only
nilandfalseare falsy — Ruby has exactly two falsy values,nilandfalse;0,0.0,"",[]and{}are all truthy and no class… - fiber →
Thread.current[:x]is fiber-local, not thread-local —Thread.current[:x]is scoped to the fiber that set it - fibers → A Fiber is a coroutine you resume by hand —
Fiber.new { }makes a block that runs only when youresumeit and stops wherever it callsFiber.yield; values… - fibers →
Enumerator#nextruns the block on its own Fiber —each,to_a,mapandfirstrun anEnumerator's block where they are called, on the calling fiber;next… - fibers are coroutines → A Fiber is a coroutine you resume by hand —
Fiber.new { }makes a block that runs only when youresumeit and stops wherever it callsFiber.yield; values… - file →
File.openwith a block closes the file for you —File.open(name, mode) { |f| … }closes the file when the block ends and evaluates to the block's value; Python's… - file open with a block →
File.openwith a block closes the file for you —File.open(name, mode) { |f| … }closes the file when the block ends and evaluates to the block's value; Python's… File.openwith a block closes the file for you —File.open(name, mode) { |f| … }closes the file when the block ends and evaluates to the block's value; Python's…- flags → The command line is part of the language —
rubytakes flags for running code (-e), checking it (-c), warning about it (-w,-W:category), loading… - float →
1 == 1.0is true, but{1 => :a}[1.0]isnil— Ruby's==compares an Integer with a Float by value - floats →
0.1 + 0.2 != 0.3, and2.5.roundis3— A Ruby Float is the same 64-bit double as a Python float - floats and rounding →
0.1 + 0.2 != 0.3, and2.5.roundis3— A Ruby Float is the same 64-bit double as a Python float - floors →
7 / 2is3: integer division floors — Ruby's/on two Integers is Python's// - for loops do not scope →
forloops do not make a scope —forandwhileare syntax and open no scope forloops do not make a scope —forandwhileare syntax and open no scope- fork →
forkcopies the process;waitcollects its status —forkmakes a second process that is a copy of this one forkcopies the process;waitcollects its status —forkmakes a second process that is a copy of this one- formatting → Numbers become text with
format,to_s(16)and%—formatspeaks C's mini-language - formatting →
#{}callsto_s;formatis printf —"#{expr}"evaluates any expression and callsto_son the result - forms →
raisehas four forms —raise "msg"is aRuntimeError,raise Klassan instance whose message is the class name,raise Klass, "msg"… - four → Ruby has four kinds of equality —
equal?is identity,==is value,eql?is value without type conversion (the testHashkeys use), and===… - four →
raisehas four forms —raise "msg"is aRuntimeError,raise Klassan instance whose message is the class name,raise Klass, "msg"… - four kinds of equality → Ruby has four kinds of equality —
equal?is identity,==is value,eql?is value without type conversion (the testHashkeys use), and===… - freeze →
freezeis shallow and raisesFrozenError—freezemakes one object immutable - freeze and frozen error →
freezeis shallow and raisesFrozenError—freezemakes one object immutable freezeis shallow and raisesFrozenError—freezemakes one object immutable- frozen →
dupis a fresh copy,cloneis a faithful one —dupandcloneboth make a new object with the same instance variables, and both are shallow - frozen →
freezeis shallow and raisesFrozenError—freezemakes one object immutable
G¶
- gemfile → Gems are versioned; Bundler pins them — A gem is a versioned package that RubyGems can activate by name (
gem "x"), some ship inside Ruby (default gems),… - gems → Gems are versioned; Bundler pins them — A gem is a versioned package that RubyGems can activate by name (
gem "x"), some ship inside Ruby (default gems),… - Gems are versioned; Bundler pins them — A gem is a versioned package that RubyGems can activate by name (
gem "x"), some ship inside Ruby (default gems),… - gems bundler and gemfile → Gems are versioned; Bundler pins them — A gem is a versioned package that RubyGems can activate by name (
gem "x"), some ship inside Ruby (default gems),… - gets →
getsreturns nil at EOF, and readsARGV's files first —getsreturns the next line with its newline andnilat end of input getsreturns nil at EOF, and readsARGV's files first —getsreturns the next line with its newline andnilat end of input- glob →
Pathname#/joins, andDir.globis sorted —Pathnameis an object with/,basename,extname,parent,children,exist?andread;Dir.glob… - gotchas → Twenty-three Python traps for a Ruby programmer — The twenty-three places where a Ruby reflex gives the wrong answer in Python
- gotchas → Twenty-three Ruby traps for a Python programmer — The twenty-three places where a Python reflex gives the wrong answer in Ruby
- gotchas for python programmers → Twenty-three Ruby traps for a Python programmer — The twenty-three places where a Python reflex gives the wrong answer in Ruby
- gotchas for ruby programmers in python → Twenty-three Python traps for a Ruby programmer — The twenty-three places where a Ruby reflex gives the wrong answer in Python
- guards → A pin compares; a bare name binds — Inside a pattern a bare name always binds
- guards →
x ||= vassigns whenxis nil or false —x ||= visx || (x = v): it assigns whenxisnilorfalseand leaves every other value alone, so it… - gvl → Threads are OS threads that take turns under the GVL —
Thread.new { }starts a real OS thread that shares every object with the others;joinwaits and re-raises…
H¶
- haproxy → A
SizedQueuethat refuses is the 503 behind "queue full" — Passenger answers a Rails app's requests from a fixed pool of processes, 6 by default, through a request queue with a… - hash → A Hash key needs
eql?andhash, not==— AHashfinds a key by callinghashand theneql? - hashes → A missing key is nil, and
Hash.new([])shares its default —h[:zz]isnilwhered["zz"]raisesKeyError;fetchis the raising form;Hash.new(0)returns a default… - hashes and default values → A missing key is nil, and
Hash.new([])shares its default —h[:zz]isnilwhered["zz"]raisesKeyError;fetchis the raising form;Hash.new(0)returns a default… - hooks → Hooks fire when code is defined, not when it runs —
inherited,included,extended,prepended,method_added,singleton_method_addedandconst_addedare… - Hooks fire when code is defined, not when it runs —
inherited,included,extended,prepended,method_added,singleton_method_addedandconst_addedare… - hooks inherited included method added → Hooks fire when code is defined, not when it runs —
inherited,included,extended,prepended,method_added,singleton_method_addedandconst_addedare…
I¶
- implicit →
selfis the implicit receiver — Every Ruby call has a receiver, and when you write none it isself - include → Mixins:
include,extend,prepend—includeinserts a module into the class's ancestor chain behind the class,prependinserts it in front so… - included → Hooks fire when code is defined, not when it runs —
inherited,included,extended,prepended,method_added,singleton_method_addedandconst_addedare… - Indentation is convention in Ruby, syntax in Python — Ruby runs mis-indented code and
ruby -wonly warns when anendsits under the wrong column, while Python refuses… - indexes → Past the end, an array gives nil, not an error —
a[10]on a four-element array isnil,a[5] = 99pads the gap withnil, and a slice isa[1..2](end… - inherited → Hooks fire when code is defined, not when it runs —
inherited,included,extended,prepended,method_added,singleton_method_addedandconst_addedare… - initialize →
newisallocatetheninitialize—Point.new(1, 2)is a class method that does two things - inject →
injectmakes the block's value the next accumulator —injectfeeds each block result back in as the accumulator, so a block that ends in an assignment hands the next… - inject and each with object →
injectmakes the block's value the next accumulator —injectfeeds each block result back in as the accumulator, so a block that ends in an assignment hands the next… injectmakes the block's value the next accumulator —injectfeeds each block result back in as the accumulator, so a block that ends in an assignment hands the next…- inspect →
putscallsto_s,pcallsinspect— Every object answers two questions - instance → Instance variables are private — An
@variablebelongs to one object and can be read or written only by that object's own methods - instance →
instance_evalmovesself,class_evalmovesdef— Both evals run a block withselfset to the receiver; the difference is where adefinside lands - instance eval and class eval →
instance_evalmovesself,class_evalmovesdef— Both evals run a block withselfset to the receiver; the difference is where adefinside lands - Instance variables are private — An
@variablebelongs to one object and can be read or written only by that object's own methods instance_evalmovesself,class_evalmovesdef— Both evals run a block withselfset to the receiver; the difference is where adefinside lands- int →
1 == 1.0is true, but{1 => :a}[1.0]isnil— Ruby's==compares an Integer with a Float by value - integer →
7 / 2is3: integer division floors — Ruby's/on two Integers is Python's// - integer division floors →
7 / 2is3: integer division floors — Ruby's/on two Integers is Python's// - integers → Integers never overflow:
2 ** 200is just an Integer — Ruby has oneIntegerclass with no ceiling - integers are unbounded → Integers never overflow:
2 ** 200is just an Integer — Ruby has oneIntegerclass with no ceiling - Integers never overflow:
2 ** 200is just an Integer — Ruby has oneIntegerclass with no ceiling - interpolation →
#{}callsto_s;formatis printf —"#{expr}"evaluates any expression and callsto_son the result - interpreter → YJIT and ZJIT are switches, not defaults — MRI (
RUBY_ENGINE == "ruby") always runs YARV bytecode through its interpreter; YJIT (since 3.1) and ZJIT (new in… - introspection → An object can list its methods and variables —
methods,instance_methods(false),instance_variables,instance_method(:x).parameters,source_location,… - irb →
irbechoes every value; a script does not —irbis a read–eval–print loop: each line's value is printed withinspect,_holds the last one, an exception… - irb and the repl →
irbechoes every value; a script does not —irbis a read–eval–print loop: each line's value is printed withinspect,_holds the last one, an exception… irbechoes every value; a script does not —irbis a read–eval–print loop: each line's value is printed withinspect,_holds the last one, an exception…- it and numbered parameters →
itand_1name the block's parameter — A block with no|x|can read its arguments as_1,_2, … (Ruby 2.7) or asit(Ruby 3.4); they are parameters… itand_1name the block's parameter — A block with no|x|can read its arguments as_1,_2, … (Ruby 2.7) or asit(Ruby 3.4); they are parameters…- iterator → An iterator is a method that yields — A class earns the whole
Enumerabletoolbox by writing oneeachthat yields and including the module; `return…
J¶
- jits → YJIT and ZJIT are switches, not defaults — MRI (
RUBY_ENGINE == "ruby") always runs YARV bytecode through its interpreter; YJIT (since 3.1) and ZJIT (new in… - jits and the interpreter → YJIT and ZJIT are switches, not defaults — MRI (
RUBY_ENGINE == "ruby") always runs YARV bytecode through its interpreter; YJIT (since 3.1) and ZJIT (new in… - json →
JSON.parsegives string keys;YAML.loadis safe — JSON is text for everyone and loses what JSON cannot say - json yaml and marshal →
JSON.parsegives string keys;YAML.loadis safe — JSON is text for everyone and loses what JSON cannot say JSON.parsegives string keys;YAML.loadis safe — JSON is text for everyone and loses what JSON cannot say
K¶
- kernel →
Objectsits onKernelonBasicObject—Object.ancestorsis[Object, Kernel, BasicObject]andObjectitself defines no public methods - keys → A Hash key needs
eql?andhash, not==— AHashfinds a key by callinghashand theneql? - keys → A string key and a symbol key are two keys —
{"a" => 1}[:a]isnilbecause"a"and:aare different objects of different classes,JSON.parsealways… - keys →
deconstructanddeconstruct_keyslet any object be matched — An array pattern calls the subject'sdeconstructand a hash pattern callsdeconstruct_keys(keys) - keyword → Arguments: positional, keyword, splat and block — A Ruby parameter list has eight kinds of slot
- killing →
Timeout.timeoutinterrupts a thread from outside —Timeout.timeout(0.2) { sleep 5 }raisesTimeout::Errorafter a fifth of a second because a watcher thread calls… - kinds → Ruby has four kinds of equality —
equal?is identity,==is value,eql?is value without type conversion (the testHashkeys use), and===…
L¶
- lambdas → Procs and lambdas differ in arity and
return— Every proc and lambda is aProc, but a lambda checks its argument count andreturns from itself, while a proc… - last → The last expression is the return value — A Ruby method returns the value of the last expression it evaluated, so
returnis only for leaving early - lazy →
lazyruns the chain one element at a time —mapandselecton an ordinary collection each run to the end and build an array before the next stage starts;… - lazy enumerators →
lazyruns the chain one element at a time —mapandselecton an ordinary collection each run to the end and build an array before the next stage starts;… lazyruns the chain one element at a time —mapandselecton an ordinary collection each run to the end and build an array before the next stage starts;…- lexical → Constants are found lexically, then through ancestors — A bare constant name is resolved by the lexical nesting the code was written in (
Module.nesting), then through the… - library → Text lives in the Ruby text library — a Ruby
Stringis bytes plus an encoding label - line → The command line is part of the language —
rubytakes flags for running code (-e), checking it (-c), warning about it (-w,-W:category), loading… - lives → Text lives in the Ruby text library — a Ruby
Stringis bytes plus an encoding label - load →
requireloads once;loadruns every time —requireandrequire_relativerun a file once and remember it in$LOADED_FEATURES;loadruns a file every… - load shedding → A
SizedQueuethat refuses is the 503 behind "queue full" — Passenger answers a Rails app's requests from a fixed pool of processes, 6 by default, through a request queue with a… - locals →
Thread.current[:x]is fiber-local, not thread-local —Thread.current[:x]is scoped to the fiber that set it - lookup → Method lookup walks
ancestors;supercontinues it — A call searches the receiver'sancestorsfrom left to right and stops at the first class or module that defines… - loops →
forloops do not make a scope —forandwhileare syntax and open no scope
M¶
- marshal →
JSON.parsegives string keys;YAML.loadis safe — JSON is text for everyone and loses what JSON cannot say - matching → Nothing matched:
case/inraises,case/whenreturnsnil— Acase/inwith no matching branch and noelse, and a rightwardvalue => pattern, raiseNoMatchingPatternError - matching →
case/inmatches shape, not just value —case … intests a value against a pattern - means →
privatemeans "no receiver" — A private method can be called only without an explicit receiver (or withself.), a protected method only from… - messages → Common error messages — Twenty-nine errors you will meet in your first month of Ruby, each with the code that raises it, the message Ruby…
- method → A method is a value once you ask for it —
obj.method(:name)hands back aMethodbound toobj, andKlass.instance_method(:name)anUnboundMethodyou… - method → Hooks fire when code is defined, not when it runs —
inherited,included,extended,prepended,method_added,singleton_method_addedandconst_addedare… - method → Method lookup walks
ancestors;supercontinues it — A call searches the receiver'sancestorsfrom left to right and stops at the first class or module that defines… - method →
define_methodturns a block into a method —define_method(:name) { ... }installs a method whose body is a closure - method →
method_missingneedsrespond_to_missing?—method_missing(name, *args)runs only after normal lookup has failed, and it must callsuperfor names it does… - method lookup and super → Method lookup walks
ancestors;supercontinues it — A call searches the receiver'sancestorsfrom left to right and stops at the first class or module that defines… - Method lookup walks
ancestors;supercontinues it — A call searches the receiver'sancestorsfrom left to right and stops at the first class or module that defines… - method missing and respond to missing →
method_missingneedsrespond_to_missing?—method_missing(name, *args)runs only after normal lookup has failed, and it must callsuperfor names it does… - method objects and unbound methods → A method is a value once you ask for it —
obj.method(:name)hands back aMethodbound toobj, andKlass.instance_method(:name)anUnboundMethodyou… method_missingneedsrespond_to_missing?—method_missing(name, *args)runs only after normal lookup has failed, and it must callsuperfor names it does…- methods → A method is a value once you ask for it —
obj.method(:name)hands back aMethodbound toobj, andKlass.instance_method(:name)anUnboundMethodyou… - methods → Bang means dangerous, question mark means predicate — A trailing
!marks the more dangerous of two versions of a method - methods → Operators are methods, except the ones that are not —
+,-@,[],[]=,<=>,<<and even!are ordinary methods you define withdef, and1 + 2is1.+(2) - minitest → A Minitest test is a plain class — Minitest, a bundled gem, runs every
test_*method of aMinitest::Testsubclass in a seeded random order and… - minitest and unittest → A Minitest test is a plain class — Minitest, a bundled gem, runs every
test_*method of aMinitest::Testsubclass in a seeded random order and… - missing →
method_missingneedsrespond_to_missing?—method_missing(name, *args)runs only after normal lookup has failed, and it must callsuperfor names it does… - mixin → Enumerable is a mixin: write
each, get the rest — A class that defineseachand saysinclude Enumerablegainsmap,select,sort_by,min_by,include?,… - mixins → Mixins:
include,extend,prepend—includeinserts a module into the class's ancestor chain behind the class,prependinserts it in front so… - mixins include extend prepend → Mixins:
include,extend,prepend—includeinserts a module into the class's ancestor chain behind the class,prependinserts it in front so… - Mixins:
include,extend,prepend—includeinserts a module into the class's ancestor chain behind the class,prependinserts it in front so… - modifier →
rescueworks as a modifier, forStandardErroronly —expr rescue fallbackevaluatesexprand, if it raises aStandardError, yieldsfallbackinstead; it binds… - modifiers →
unlessnegatesif; modifiers hang off the end of a line — Ruby spellsif notasunlessandwhile notasuntil, lets any statement carryif,unless,whileor… - modules → A module is a namespace, and cannot be instantiated —
module Shopis a named box for classes, constants and methods - modules as namespaces → A module is a namespace, and cannot be instantiated —
module Shopis a named box for classes, constants and methods - Most loops you would write are one Enumerable call —
map,select,reject,find,partition,group_by,tally,each_slice,each_cons,zip,flat_map,… - multiple →
return a, breturns one Array — Ruby has no tuple:return a, bbuilds an Array, multiple assignment takes it apart, and a count mismatch silently… - multiple return values →
return a, breturns one Array — Ruby has no tuple:return a, bbuilds an Array, multiple assignment takes it apart, and a count mismatch silently… - mutable → Strings are mutable;
<<keeps the object — A RubyStringis a mutable object - mutex → Mutex guards, Queue hands over, ConditionVariable waits —
Mutex#synchronizemakescount += 1exact across ten threads, aQueuemoves work from one thread to another and… - Mutex guards, Queue hands over, ConditionVariable waits —
Mutex#synchronizemakescount += 1exact across ten threads, aQueuemoves work from one thread to another and… - mutex queue and condition variable → Mutex guards, Queue hands over, ConditionVariable waits —
Mutex#synchronizemakescount += 1exact across ten threads, aQueuemoves work from one thread to another and…
N¶
- names → A symbol is a name, not a string — A Ruby symbol is an immutable name of which exactly one object exists per spelling
- namespaces → A module is a namespace, and cannot be instantiated —
module Shopis a named box for classes, constants and methods - naming → Indentation is convention in Ruby, syntax in Python — Ruby runs mis-indented code and
ruby -wonly warns when anendsits under the wrong column, while Python refuses… - navigation →
&.skips the call when the receiver is nil —receiver&.method(args)returnsnilwithout calling anything - negative → Past the end, an array gives nil, not an error —
a[10]on a four-element array isnil,a[5] = 99pads the gap withnil, and a slice isa[1..2](end… - new →
newisallocatetheninitialize—Point.new(1, 2)is a class method that does two things - new allocate and initialize →
newisallocatetheninitialize—Point.new(1, 2)is a class method that does two things newisallocatetheninitialize—Point.new(1, 2)is a class method that does two things- next →
next,breakandreturnleave a block differently —next vends this run of the block withvas its value,break vends the method the block was given to and… - next break and return in blocks →
next,breakandreturnleave a block differently —next vends this run of the block withvas its value,break vends the method the block was given to and… next,breakandreturnleave a block differently —next vends this run of the block withvas its value,break vends the method the block was given to and…- nil → Only
nilandfalseare falsy — Ruby has exactly two falsy values,nilandfalse;0,0.0,"",[]and{}are all truthy and no class… - nil →
x ||= vassigns whenxis nil or false —x ||= visx || (x = v): it assigns whenxisnilorfalseand leaves every other value alone, so it… - nil false and truthiness → Only
nilandfalseare falsy — Ruby has exactly two falsy values,nilandfalse;0,0.0,"",[]and{}are all truthy and no class… - no docstrings → Ruby has no docstrings — A Ruby method carries no documentation at run time
- no matching pattern error → Nothing matched:
case/inraises,case/whenreturnsnil— Acase/inwith no matching branch and noelse, and a rightwardvalue => pattern, raiseNoMatchingPatternError - nothing → Ractors share nothing that is not frozen — A Ractor runs a block on a thread with a lock of its own, so two Ractors run Ruby code at the same time
- Nothing matched:
case/inraises,case/whenreturnsnil— Acase/inwith no matching branch and noelse, and a rightwardvalue => pattern, raiseNoMatchingPatternError - number → Numbers become text with
format,to_s(16)and%—formatspeaks C's mini-language - number formatting → Numbers become text with
format,to_s(16)and%—formatspeaks C's mini-language - numbered →
itand_1name the block's parameter — A block with no|x|can read its arguments as_1,_2, … (Ruby 2.7) or asit(Ruby 3.4); they are parameters… - Numbers become text with
format,to_s(16)and%—formatspeaks C's mini-language - numeric →
1 + 1.5works because Integer asks Float tocoerce— WhenInteger#+meets an operand it does not know, it calls that object'scoerceand adds the pair it gets back - numeric coercion →
1 + 1.5works because Integer asks Float tocoerce— WhenInteger#+meets an operand it does not know, it calls that object'scoerceand adds the pair it gets back
O¶
- object → Everything is an object, even
1andnil— Every Ruby value - object → The GC answers comparisons, not counts —
GC.start,GC.stat,ObjectSpaceandWeakReflet a program watch its own heap, but only comparisons are stable - object →
Objectsits onKernelonBasicObject—Object.ancestorsis[Object, Kernel, BasicObject]andObjectitself defines no public methods - object →
injectmakes the block's value the next accumulator —injectfeeds each block result back in as the accumulator, so a block that ends in an assignment hands the next… - object space and gc → The GC answers comparisons, not counts —
GC.start,GC.stat,ObjectSpaceandWeakReflet a program watch its own heap, but only comparisons are stable Objectsits onKernelonBasicObject—Object.ancestorsis[Object, Kernel, BasicObject]andObjectitself defines no public methods- objects → A method is a value once you ask for it —
obj.method(:name)hands back aMethodbound toobj, andKlass.instance_method(:name)anUnboundMethodyou… - objects → Blocks are not objects — A block is syntax attached to one method call
- Only
nilandfalseare falsy — Ruby has exactly two falsy values,nilandfalse;0,0.0,"",[]and{}are all truthy and no class… - open → Classes are open —
class Stringwritten a second time does not make a new class - open →
File.openwith a block closes the file for you —File.open(name, mode) { |f| … }closes the file when the block ends and evaluates to the block's value; Python's… - operators → Operators are methods, except the ones that are not —
+,-@,[],[]=,<=>,<<and even!are ordinary methods you define withdef, and1 + 2is1.+(2) - operators are methods → Operators are methods, except the ones that are not —
+,-@,[],[]=,<=>,<<and even!are ordinary methods you define withdef, and1 + 2is1.+(2) - Operators are methods, except the ones that are not —
+,-@,[],[]=,<=>,<<and even!are ordinary methods you define withdef, and1 + 2is1.+(2) - optional → Parentheses are optional, but the space is not — Ruby lets you leave the parentheses off a call and off a
def, so a bare name is a call - or equals and nil guards →
x ||= vassigns whenxis nil or false —x ||= visx || (x = v): it assigns whenxisnilorfalseand leaves every other value alone, so it… - other →
systemreturns true, false or nil —systemreturnstruefor exit 0,falsefor any other status andnilwhen the command could not be started;…
P¶
- parameters →
itand_1name the block's parameter — A block with no|x|can read its arguments as_1,_2, … (Ruby 2.7) or asit(Ruby 3.4); they are parameters… - parentheses → Parentheses are optional, but the space is not — Ruby lets you leave the parentheses off a call and off a
def, so a bare name is a call - parentheses are optional → Parentheses are optional, but the space is not — Ruby lets you leave the parentheses off a call and off a
def, so a bare name is a call - Parentheses are optional, but the space is not — Ruby lets you leave the parentheses off a call and off a
def, so a bare name is a call - passenger → A
SizedQueuethat refuses is the 503 behind "queue full" — Passenger answers a Rails app's requests from a fixed pool of processes, 6 by default, through a request queue with a… - Past the end, an array gives nil, not an error —
a[10]on a four-element array isnil,a[5] = 99pads the gap withnil, and a slice isa[1..2](end… - pathname →
Pathname#/joins, andDir.globis sorted —Pathnameis an object with/,basename,extname,parent,children,exist?andread;Dir.glob… - pathname dir and glob →
Pathname#/joins, andDir.globis sorted —Pathnameis an object with/,basename,extname,parent,children,exist?andread;Dir.glob… Pathname#/joins, andDir.globis sorted —Pathnameis an object with/,basename,extname,parent,children,exist?andread;Dir.glob…- pattern → Nothing matched:
case/inraises,case/whenreturnsnil— Acase/inwith no matching branch and noelse, and a rightwardvalue => pattern, raiseNoMatchingPatternError - pattern →
case/inmatches shape, not just value —case … intests a value against a pattern - pin → A pin compares; a bare name binds — Inside a pattern a bare name always binds
- pin guards and alternatives → A pin compares; a bare name binds — Inside a pattern a bare name always binds
- positional → Arguments: positional, keyword, splat and block — A Ruby parameter list has eight kinds of slot
- precedence →
and/orbind lower than=— Ruby has two pairs of boolean operators - prepend → Mixins:
include,extend,prepend—includeinserts a module into the class's ancestor chain behind the class,prependinserts it in front so… - print →
putsadds a newline,printdoes not,pshowsinspect—putswritesto_splus a newline it does not double, flattening arrays, printingnilas an empty line and an… - private → Instance variables are private — An
@variablebelongs to one object and can be read or written only by that object's own methods - private →
privatemeans "no receiver" — A private method can be called only without an explicit receiver (or withself.), a protected method only from… - private means no receiver →
privatemeans "no receiver" — A private method can be called only without an explicit receiver (or withself.), a protected method only from… privatemeans "no receiver" — A private method can be called only without an explicit receiver (or withself.), a protected method only from…- proc →
&:symcallsSymbol#to_proc—&xin an argument list callsx.to_procand attaches the result as the block; a symbol'sto_procis a lambda… - processes →
forkcopies the process;waitcollects its status —forkmakes a second process that is a copy of this one - processes fork and wait →
forkcopies the process;waitcollects its status —forkmakes a second process that is a copy of this one - procs → Procs and lambdas differ in arity and
return— Every proc and lambda is aProc, but a lambda checks its argument count andreturns from itself, while a proc… - procs and lambdas differ → Procs and lambdas differ in arity and
return— Every proc and lambda is aProc, but a lambda checks its argument count andreturns from itself, while a proc… - Procs and lambdas differ in arity and
return— Every proc and lambda is aProc, but a lambda checks its argument count andreturns from itself, while a proc… - Procs curry and compose —
Proc#curryturns an n-argument lambda into a chain of one-argument lambdas,>>and<<compose any two… - programmers → Twenty-three Python traps for a Ruby programmer — The twenty-three places where a Ruby reflex gives the wrong answer in Python
- programmers → Twenty-three Ruby traps for a Python programmer — The twenty-three places where a Python reflex gives the wrong answer in Ruby
- programs →
systemreturns true, false or nil —systemreturnstruefor exit 0,falsefor any other status andnilwhen the command could not be started;… - public →
sendreaches private methods;public_senddoes not —obj.send(:name, *args)calls a method by name and ignores visibility,public_sendhonours it, and__send__… - puts →
putsadds a newline,printdoes not,pshowsinspect—putswritesto_splus a newline it does not double, flattening arrays, printingnilas an empty line and an… - puts print p and pp →
putsadds a newline,printdoes not,pshowsinspect—putswritesto_splus a newline it does not double, flattening arrays, printingnilas an empty line and an… putsadds a newline,printdoes not,pshowsinspect—putswritesto_splus a newline it does not double, flattening arrays, printingnilas an empty line and an…putscallsto_s,pcallsinspect— Every object answers two questions- python → Twenty-three Python traps for a Ruby programmer — The twenty-three places where a Ruby reflex gives the wrong answer in Python
- python → Twenty-three Ruby traps for a Python programmer — The twenty-three places where a Python reflex gives the wrong answer in Ruby
- pythonic → There is more than one way, and one obvious way — Ruby's idioms
Q¶
- question → Bang means dangerous, question mark means predicate — A trailing
!marks the more dangerous of two versions of a method - queue → A
SizedQueuethat refuses is the 503 behind "queue full" — Passenger answers a Rails app's requests from a fixed pool of processes, 6 by default, through a request queue with a… - queue → Mutex guards, Queue hands over, ConditionVariable waits —
Mutex#synchronizemakescount += 1exact across ten threads, aQueuemoves work from one thread to another and… - queue full → A
SizedQueuethat refuses is the 503 behind "queue full" — Passenger answers a Rails app's requests from a fixed pool of processes, 6 by default, through a request queue with a…
R¶
- ractors → Ractors share nothing that is not frozen — A Ractor runs a block on a thread with a lock of its own, so two Ractors run Ruby code at the same time
- ractors share nothing → Ractors share nothing that is not frozen — A Ractor runs a block on a thread with a lock of its own, so two Ractors run Ruby code at the same time
- Ractors share nothing that is not frozen — A Ractor runs a block on a thread with a lock of its own, so two Ractors run Ruby code at the same time
- raise →
raisehas four forms —raise "msg"is aRuntimeError,raise Klassan instance whose message is the class name,raise Klass, "msg"… - raise has four forms →
raisehas four forms —raise "msg"is aRuntimeError,raise Klassan instance whose message is the class name,raise Klass, "msg"… raisehas four forms —raise "msg"is aRuntimeError,raise Klassan instance whose message is the class name,raise Klass, "msg"…- random →
Random.new(42)gives the same numbers every run — A seededRandomis a function of its seed - random with a seed →
Random.new(42)gives the same numbers every run — A seededRandomis a function of its seed Random.new(42)gives the same numbers every run — A seededRandomis a function of its seed- ranges → Two dots include the end, three dots exclude it —
1..5is five numbers and1...5is four; a Range can be endless (1..), beginless (..5), made of Strings… - ranges two dots and three → Two dots include the end, three dots exclude it —
1..5is five numbers and1...5is four; a Range can be endless (1..), beginless (..5), made of Strings… - rational →
1/3randBigDecimal("0.1")are exact where Float is not — Ruby ships two exact number types beside Float - rational and bigdecimal →
1/3randBigDecimal("0.1")are exact where Float is not — Ruby ships two exact number types beside Float - receiver →
privatemeans "no receiver" — A private method can be called only without an explicit receiver (or withself.), a protected method only from… - references → A variable is a reference, not a box — Assignment copies a reference, never the object, so after
b = aa mutating method such as<<onbis seen… - refinements → Refinements are lexical, not global —
refine String do … endinside a module builds aRefinement, andusingthat module activates it from that line… - Refinements are lexical, not global —
refine String do … endinside a module builds aRefinement, andusingthat module activates it from that line… - refuses → A
SizedQueuethat refuses is the 503 behind "queue full" — Passenger answers a Rails app's requests from a fixed pool of processes, 6 by default, through a request queue with a… - relative →
requireloads once;loadruns every time —requireandrequire_relativerun a file once and remember it in$LOADED_FEATURES;loadruns a file every… - repl →
irbechoes every value; a script does not —irbis a read–eval–print loop: each line's value is printed withinspect,_holds the last one, an exception… - require →
requireloads once;loadruns every time —requireandrequire_relativerun a file once and remember it in$LOADED_FEATURES;loadruns a file every… - require require relative and load →
requireloads once;loadruns every time —requireandrequire_relativerun a file once and remember it in$LOADED_FEATURES;loadruns a file every… requireloads once;loadruns every time —requireandrequire_relativerun a file once and remember it in$LOADED_FEATURES;loadruns a file every…- rescue →
rescueworks as a modifier, forStandardErroronly —expr rescue fallbackevaluatesexprand, if it raises aStandardError, yieldsfallbackinstead; it binds… - rescue →
rescue,elseandensurerun in a fixed order — The body runs first; thenrescueif it raised orelseif it did not; thenensure, always - rescue as a modifier →
rescueworks as a modifier, forStandardErroronly —expr rescue fallbackevaluatesexprand, if it raises aStandardError, yieldsfallbackinstead; it binds… - rescue ensure else and retry →
rescue,elseandensurerun in a fixed order — The body runs first; thenrescueif it raised orelseif it did not; thenensure, always rescueworks as a modifier, forStandardErroronly —expr rescue fallbackevaluatesexprand, if it raises aStandardError, yieldsfallbackinstead; it binds…rescue,elseandensurerun in a fixed order — The body runs first; thenrescueif it raised orelseif it did not; thenensure, always- respond → Duck typing asks
respond_to?, notclass— Ruby code asks an object what it can do - respond →
method_missingneedsrespond_to_missing?—method_missing(name, *args)runs only after normal lookup has failed, and it must callsuperfor names it does… - retry →
rescue,elseandensurerun in a fixed order — The body runs first; thenrescueif it raised orelseif it did not; thenensure, always - return → A setter returns its argument, not its body —
obj.x = 5is a call to the methodx=, but as an expression it evaluates to 5 whatever the method body returns - return →
next,breakandreturnleave a block differently —next vends this run of the block withvas its value,break vends the method the block was given to and… - return →
return a, breturns one Array — Ruby has no tuple:return a, bbuilds an Array, multiple assignment takes it apart, and a count mismatch silently… return a, breturns one Array — Ruby has no tuple:return a, bbuilds an Array, multiple assignment takes it apart, and a count mismatch silently…- rounding →
0.1 + 0.2 != 0.3, and2.5.roundis3— A Ruby Float is the same 64-bit double as a Python float - ruby → There is more than one way, and one obvious way — Ruby's idioms
- ruby → Twenty-three Python traps for a Ruby programmer — The twenty-three places where a Ruby reflex gives the wrong answer in Python
- ruby → What changed, 1.9 to 4.0 — Ruby's releases each added a few things you will meet in old code and new
- Ruby has block comments and a data section — Ruby comments with
#, with=begin/=endblocks that must start at column 0, and with magic comments the parser… - Ruby has four kinds of equality —
equal?is identity,==is value,eql?is value without type conversion (the testHashkeys use), and===… - Ruby has no docstrings — A Ruby method carries no documentation at run time
- Ruby shows you its bytecode and its syntax tree —
RubyVM::InstructionSequence.compile(src).disasmlists the YARV instructions the interpreter will execute and… - ruby versions what changed → What changed, 1.9 to 4.0 — Ruby's releases each added a few things you will meet in old code and new
- run →
Enumerator#nextruns the block on its own Fiber —each,to_a,mapandfirstrun anEnumerator's block where they are called, on the calling fiber;next… - running →
systemreturns true, false or nil —systemreturnstruefor exit 0,falsefor any other status andnilwhen the command could not be started;… - running other programs →
systemreturns true, false or nil —systemreturnstruefor exit 0,falsefor any other status andnilwhen the command could not be started;… - runtime →
Class.newmakes a class; a constant names it —Class.new(Base) { ... }returns a class object with no name,Foo = klassgives it the name of the first constant…
S¶
- safe →
&.skips the call when the receiver is nil —receiver&.method(args)returnsnilwithout calling anything - safe navigation →
&.skips the call when the receiver is nil —receiver&.method(args)returnsnilwithout calling anything - scope → Constants are found lexically, then through ancestors — A bare constant name is resolved by the lexical nesting the code was written in (
Module.nesting), then through the… - scope →
forloops do not make a scope —forandwhileare syntax and open no scope - see → Ruby shows you its bytecode and its syntax tree —
RubyVM::InstructionSequence.compile(src).disasmlists the YARV instructions the interpreter will execute and… - seed →
Random.new(42)gives the same numbers every run — A seededRandomis a function of its seed - self →
selfis the implicit receiver — Every Ruby call has a receiver, and when you write none it isself - self is implicit →
selfis the implicit receiver — Every Ruby call has a receiver, and when you write none it isself selfis the implicit receiver — Every Ruby call has a receiver, and when you write none it isself- send →
sendreaches private methods;public_senddoes not —obj.send(:name, *args)calls a method by name and ignores visibility,public_sendhonours it, and__send__… - send and public send →
sendreaches private methods;public_senddoes not —obj.send(:name, *args)calls a method by name and ignores visibility,public_sendhonours it, and__send__… sendreaches private methods;public_senddoes not —obj.send(:name, *args)calls a method by name and ignores visibility,public_sendhonours it, and__send__…- set → Set is a core class in 4.0 and keeps insertion order — In Ruby 4.0
Setneeds norequireand is written in C,Set[3, 1, 2]iterates as 3, 1, 2, and an element is… - set is a core class → Set is a core class in 4.0 and keeps insertion order — In Ruby 4.0
Setneeds norequireand is written in C,Set[3, 1, 2]iterates as 3, 1, 2, and an element is… - Set is a core class in 4.0 and keeps insertion order — In Ruby 4.0
Setneeds norequireand is written in C,Set[3, 1, 2]iterates as 3, 1, 2, and an element is… - setters → A setter returns its argument, not its body —
obj.x = 5is a call to the methodx=, but as an expression it evaluates to 5 whatever the method body returns - setters return the argument → A setter returns its argument, not its body —
obj.x = 5is a call to the methodx=, but as an expression it evaluates to 5 whatever the method body returns - share → Ractors share nothing that is not frozen — A Ractor runs a block on a thread with a lock of its own, so two Ractors run Ruby code at the same time
- shared → Class variables are shared with subclasses —
@@countis one variable, owned by the class that first assigns it and seen by every subclass and every instance - singleton → Every object has a class of its own — A method defined on one object
- singleton classes → Every object has a class of its own — A method defined on one object
- sized → A
SizedQueuethat refuses is the 503 behind "queue full" — Passenger answers a Rails app's requests from a fixed pool of processes, 6 by default, through a request queue with a… - sized queue → A
SizedQueuethat refuses is the 503 behind "queue full" — Passenger answers a Rails app's requests from a fixed pool of processes, 6 by default, through a request queue with a… - sort →
sort_bykeys once,sortmany times, neither is stable —sort_bycomputes each element's key exactly once andsort { |a, b| … }recomputes at every comparison, but Ruby… - sort stability and sort by →
sort_bykeys once,sortmany times, neither is stable —sort_bycomputes each element's key exactly once andsort { |a, b| … }recomputes at every comparison, but Ruby… sort_bykeys once,sortmany times, neither is stable —sort_bycomputes each element's key exactly once andsort { |a, b| … }recomputes at every comparison, but Ruby…- space → The GC answers comparisons, not counts —
GC.start,GC.stat,ObjectSpaceandWeakReflet a program watch its own heap, but only comparisons are stable - spaceship → Define
<=>and Comparable gives you the rest —<=>answers-1,0,1ornil("these do not compare");include Comparableturns that one method into<,… - splat → Arguments: positional, keyword, splat and block — A Ruby parameter list has eight kinds of slot
- stability →
sort_bykeys once,sortmany times, neither is stable —sort_bycomputes each element's key exactly once andsort { |a, b| … }recomputes at every comparison, but Ruby… - standard → A bare
rescuecatchesStandardError, not everything —rescuewith no class list meansrescue StandardError, andSystemExit,Interrupt,NoMemoryError,… - standard error is the default → A bare
rescuecatchesStandardError, not everything —rescuewith no class list meansrescue StandardError, andSystemExit,Interrupt,NoMemoryError,… - state →
dupis a fresh copy,cloneis a faithful one —dupandcloneboth make a new object with the same instance variables, and both are shallow - status →
ARGVholds strings andENVis not a Hash —ARGVis an Array of Strings,$0is the script name as it was invoked,ENVis a Hash-like object whose values… - stdin →
getsreturns nil at EOF, and readsARGV's files first —getsreturns the next line with its newline andnilat end of input - stdin gets and argf →
getsreturns nil at EOF, and readsARGV's files first —getsreturns the next line with its newline andnilat end of input - string → A string key and a symbol key are two keys —
{"a" => 1}[:a]isnilbecause"a"and:aare different objects of different classes,JSON.parsealways… - string →
#{}callsto_s;formatis printf —"#{expr}"evaluates any expression and callsto_son the result - string and symbol keys → A string key and a symbol key are two keys —
{"a" => 1}[:a]isnilbecause"a"and:aare different objects of different classes,JSON.parsealways… - string formatting and interpolation →
#{}callsto_s;formatis printf —"#{expr}"evaluates any expression and callsto_son the result - strings → Strings are mutable;
<<keeps the object — A RubyStringis a mutable object - strings are mutable → Strings are mutable;
<<keeps the object — A RubyStringis a mutable object - Strings are mutable;
<<keeps the object — A RubyStringis a mutable object - struct → Struct is mutable, Data is not —
Struct.new(:x, :y)makes a record you can build positionally or by keyword and then change; `Data.define(:lat,… - struct and data → Struct is mutable, Data is not —
Struct.new(:x, :y)makes a record you can build positionally or by keyword and then change; `Data.define(:lat,… - Struct is mutable, Data is not —
Struct.new(:x, :y)makes a record you can build positionally or by keyword and then change; `Data.define(:lat,… - style → Indentation is convention in Ruby, syntax in Python — Ruby runs mis-indented code and
ruby -wonly warns when anendsits under the wrong column, while Python refuses… - style and naming → Indentation is convention in Ruby, syntax in Python — Ruby runs mis-indented code and
ruby -wonly warns when anendsits under the wrong column, while Python refuses… - super → Method lookup walks
ancestors;supercontinues it — A call searches the receiver'sancestorsfrom left to right and stops at the first class or module that defines… - symbol → A string key and a symbol key are two keys —
{"a" => 1}[:a]isnilbecause"a"and:aare different objects of different classes,JSON.parsealways… - symbol →
&:symcallsSymbol#to_proc—&xin an argument list callsx.to_procand attaches the result as the block; a symbol'sto_procis a lambda… - symbol to proc →
&:symcallsSymbol#to_proc—&xin an argument list callsx.to_procand attaches the result as the block; a symbol'sto_procis a lambda… - symbols → A symbol is a name, not a string — A Ruby symbol is an immutable name of which exactly one object exists per spelling
- symbols are names → A symbol is a name, not a string — A Ruby symbol is an immutable name of which exactly one object exists per spelling
- system →
exitraisesSystemExit—exitis not a system call but araiseofSystemExit, soensureclauses andat_exithandlers run, a `rescue… systemreturns true, false or nil —systemreturnstruefor exit 0,falsefor any other status andnilwhen the command could not be started;…
T¶
- tap →
tapreturns the receiver,thenreturns the block's value —x.tap { … }yieldsxto the block and returnsxwhatever the block returned, so a debuggingputscan sit… - tap then and chaining →
tapreturns the receiver,thenreturns the block's value —x.tap { … }yieldsxto the block and returnsxwhatever the block returned, so a debuggingputscan sit… tapreturns the receiver,thenreturns the block's value —x.tap { … }yieldsxto the block and returnsxwhatever the block returned, so a debuggingputscan sit…- text → Text lives in the Ruby text library — a Ruby
Stringis bytes plus an encoding label - Text lives in the Ruby text library — a Ruby
Stringis bytes plus an encoding label - text lives in the text library → Text lives in the Ruby text library — a Ruby
Stringis bytes plus an encoding label - the bytecode you can see → Ruby shows you its bytecode and its syntax tree —
RubyVM::InstructionSequence.compile(src).disasmlists the YARV instructions the interpreter will execute and… - the command line flags → The command line is part of the language —
rubytakes flags for running code (-e), checking it (-c), warning about it (-w,-W:category), loading… - The command line is part of the language —
rubytakes flags for running code (-e), checking it (-c), warning about it (-w,-W:category), loading… - the enumerable toolbox → Most loops you would write are one Enumerable call —
map,select,reject,find,partition,group_by,tally,each_slice,each_cons,zip,flat_map,… - The GC answers comparisons, not counts —
GC.start,GC.stat,ObjectSpaceandWeakReflet a program watch its own heap, but only comparisons are stable - The last expression is the return value — A Ruby method returns the value of the last expression it evaluated, so
returnis only for leaving early - the last expression is the value → The last expression is the return value — A Ruby method returns the value of the last expression it evaluated, so
returnis only for leaving early - the ruby way and the pythonic way → There is more than one way, and one obvious way — Ruby's idioms
- There is more than one way, and one obvious way — Ruby's idioms
- thread →
Thread.current[:x]is fiber-local, not thread-local —Thread.current[:x]is scoped to the fiber that set it - thread locals are fiber locals →
Thread.current[:x]is fiber-local, not thread-local —Thread.current[:x]is scoped to the fiber that set it Thread.current[:x]is fiber-local, not thread-local —Thread.current[:x]is scoped to the fiber that set it- threads → Threads are OS threads that take turns under the GVL —
Thread.new { }starts a real OS thread that shares every object with the others;joinwaits and re-raises… - threads →
Timeout.timeoutinterrupts a thread from outside —Timeout.timeout(0.2) { sleep 5 }raisesTimeout::Errorafter a fifth of a second because a watcher thread calls… - threads and the gvl → Threads are OS threads that take turns under the GVL —
Thread.new { }starts a real OS thread that shares every object with the others;joinwaits and re-raises… - Threads are OS threads that take turns under the GVL —
Thread.new { }starts a real OS thread that shares every object with the others;joinwaits and re-raises… - threequals →
case/whenasks===, and every class answers it its own way —case x when ycallsy === x, and===is an ordinary method: a class answers withis_a?, a Range with… - throw →
throwandcatchare not exceptions —catch(:tag) { … throw :tag, value … }is a labelled non-local jump:throwunwinds to the matchingcatch, which… - throw and catch →
throwandcatchare not exceptions —catch(:tag) { … throw :tag, value … }is a labelled non-local jump:throwunwinds to the matchingcatch, which… throwandcatchare not exceptions —catch(:tag) { … throw :tag, value … }is a labelled non-local jump:throwunwinds to the matchingcatch, which…- time →
Timeis an instant,Dateis a calendar day — aTimeis a point on the timeline with an offset attached - time and date →
Timeis an instant,Dateis a calendar day — aTimeis a point on the timeline with an offset attached Timeis an instant,Dateis a calendar day — aTimeis a point on the timeline with an offset attachedTimeout.timeoutinterrupts a thread from outside —Timeout.timeout(0.2) { sleep 5 }raisesTimeout::Errorafter a fifth of a second because a watcher thread calls…- timeouts →
Timeout.timeoutinterrupts a thread from outside —Timeout.timeout(0.2) { sleep 5 }raisesTimeout::Errorafter a fifth of a second because a watcher thread calls… - timeouts and killing threads →
Timeout.timeoutinterrupts a thread from outside —Timeout.timeout(0.2) { sleep 5 }raisesTimeout::Errorafter a fifth of a second because a watcher thread calls… - to s inspect and p →
putscallsto_s,pcallsinspect— Every object answers two questions - toolbox → Most loops you would write are one Enumerable call —
map,select,reject,find,partition,group_by,tally,each_slice,each_cons,zip,flat_map,… - tracepoint → TracePoint sees every call and return —
TracePoint.new(:call, :return) { |tp| … }.enable { … }reports every method the VM enters and leaves - TracePoint sees every call and return —
TracePoint.new(:call, :return) { |tp| … }.enable { … }reports every method the VM enters and leaves - truthiness → Only
nilandfalseare falsy — Ruby has exactly two falsy values,nilandfalse;0,0.0,"",[]and{}are all truthy and no class… - Twenty-three Python traps for a Ruby programmer — The twenty-three places where a Ruby reflex gives the wrong answer in Python
- Twenty-three Ruby traps for a Python programmer — The twenty-three places where a Python reflex gives the wrong answer in Ruby
- Two dots include the end, three dots exclude it —
1..5is five numbers and1...5is four; a Range can be endless (1..), beginless (..5), made of Strings… - typing → Duck typing asks
respond_to?, notclass— Ruby code asks an object what it can do
U¶
- unbound → A method is a value once you ask for it —
obj.method(:name)hands back aMethodbound toobj, andKlass.instance_method(:name)anUnboundMethodyou… - unbounded → Integers never overflow:
2 ** 200is just an Integer — Ruby has oneIntegerclass with no ceiling - unittest → A Minitest test is a plain class — Minitest, a bundled gem, runs every
test_*method of aMinitest::Testsubclass in a seeded random order and… - unless →
unlessnegatesif; modifiers hang off the end of a line — Ruby spellsif notasunlessandwhile notasuntil, lets any statement carryif,unless,whileor… - unless until and modifiers →
unlessnegatesif; modifiers hang off the end of a line — Ruby spellsif notasunlessandwhile notasuntil, lets any statement carryif,unless,whileor… unlessnegatesif; modifiers hang off the end of a line — Ruby spellsif notasunlessandwhile notasuntil, lets any statement carryif,unless,whileor…- until →
unlessnegatesif; modifiers hang off the end of a line — Ruby spellsif notasunlessandwhile notasuntil, lets any statement carryif,unless,whileor… - uses →
case/whenasks===, and every class answers it its own way —case x when ycallsy === x, and===is an ordinary method: a class answers withis_a?, a Range with…
V¶
- value → The last expression is the return value — A Ruby method returns the value of the last expression it evaluated, so
returnis only for leaving early - values → A missing key is nil, and
Hash.new([])shares its default —h[:zz]isnilwhered["zz"]raisesKeyError;fetchis the raising form;Hash.new(0)returns a default… - values →
return a, breturns one Array — Ruby has no tuple:return a, bbuilds an Array, multiple assignment takes it apart, and a count mismatch silently… - variable → Mutex guards, Queue hands over, ConditionVariable waits —
Mutex#synchronizemakescount += 1exact across ten threads, aQueuemoves work from one thread to another and… - variables → A variable is a reference, not a box — Assignment copies a reference, never the object, so after
b = aa mutating method such as<<onbis seen… - variables → Class variables are shared with subclasses —
@@countis one variable, owned by the class that first assigns it and seen by every subclass and every instance - variables → Closures capture variables, not values — A block, proc or lambda carries the variables around it
- variables → Instance variables are private — An
@variablebelongs to one object and can be read or written only by that object's own methods - variables are references → A variable is a reference, not a box — Assignment copies a reference, never the object, so after
b = aa mutating method such as<<onbis seen… - versions → What changed, 1.9 to 4.0 — Ruby's releases each added a few things you will meet in old code and new
W¶
- wait →
forkcopies the process;waitcollects its status —forkmakes a second process that is a copy of this one - warnings → Warnings go to stderr, and
-wfinds more of them —warnprints to stderr;-wsets$VERBOSEtotrueand makes Ruby report unused variables, redefined methods,… - warnings and dash w → Warnings go to stderr, and
-wfinds more of them —warnprints to stderr;-wsets$VERBOSEtotrueand makes Ruby report unused variables, redefined methods,… - Warnings go to stderr, and
-wfinds more of them —warnprints to stderr;-wsets$VERBOSEtotrueand makes Ruby report unused variables, redefined methods,… - What changed, 1.9 to 4.0 — Ruby's releases each added a few things you will meet in old code and new
- writing → An iterator is a method that yields — A class earns the whole
Enumerabletoolbox by writing oneeachthat yields and including the module; `return… - writing an iterator → An iterator is a method that yields — A class earns the whole
Enumerabletoolbox by writing oneeachthat yields and including the module; `return…
X¶
x ||= vassigns whenxis nil or false —x ||= visx || (x = v): it assigns whenxisnilorfalseand leaves every other value alone, so it…
Y¶
- yaml →
JSON.parsegives string keys;YAML.loadis safe — JSON is text for everyone and loses what JSON cannot say - YJIT and ZJIT are switches, not defaults — MRI (
RUBY_ENGINE == "ruby") always runs YARV bytecode through its interpreter; YJIT (since 3.1) and ZJIT (new in…