liveBook · Manning

Thread#fetch

As explained in The Well-Grounded Rubyist, Fourth Edition

Thread#fetch is a Ruby method that retrieves a value from a thread by key, optionally returning a supplied default when the key is absent.

Thread#fetch retrieves a thread-specific value by key. Pass the key and, optionally, a default value for the missing-key case. Unlike direct indexing with Thread#[], fetch raises KeyError when the key is absent and no default is supplied. Keys may be symbols or strings, and values remain queryable even after the thread finishes. section 14.5.5

Fetching present and absent values

After a thread stores "Hola!" under :message, t.fetch(:message, "Greetings!") returns "Hola!". Fetching :msg with that default returns "Greetings!"; fetching :msg without a default raises KeyError. section 14.5.5

>> t = Thread.new do
        Thread.current[:message] = "Hola!"
      end
=> #<Thread:0x0000000127c31720 (irb):20 run>
>> t.join
=> #<Thread:0x0000000127c31720 (irb):20 dead>
>> t.fetch(:message, "Greetings!")          1
=> "Hola!"
>> t.fetch(:msg, "Greetings!")           2
=> "Greetings!"
>> t.fetch(:msg)                      3
Traceback (most recent call last):
…
(irb):28:in 'Thread#fetch': key not found: :me (KeyError)

Inspect the interactive sequence showing successful lookup, fallback to a supplied default, and failure without one. section 14.5.5

How The Well-Grounded Rubyist, Fourth Edition covers it

How deep it goes
Demonstrates accepted keys, optional defaults, successful lookup, and KeyError for an absent key without a default.
Examples
Uses irb-style thread snippets and a threaded rock-paper-scissors program that fetches player moves with an error default.
What it assumes
Assumes familiarity with threads and thread-key assignment while teaching optional defaults and missing-key errors.
What you can do after
Apply it via Ruby's Thread API to retrieve stored values and handle missing keys explicitly.
How it connects
Contrasts Thread#[] with thread keys and connects missing lookups to KeyError.

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.