Ruby 2.5 adds Thread#fetch method

Atul Bhosale
Jan 28, 2018 · 1 min read

Ruby 2.5 was recently released.

Ruby 2.5 has added Thread#fetch method for fetching the value of a fiber-local variable if it’s assigned otherwise it returns the default value.

>> th = Thread.new { Thread.current[:cat] = 'meow' }
=> #<Thread:0x0000556e11ebd0c8@(irb):1 run>
>> th.join
=> #<Thread:0x0000556e11ebd0c8@(irb):1 dead>
>> th.fetch(:cat, true)
=> "meow"
>> th.fetch(:dog, true)
=> true

For one argument to the Thread#fetch:

  1. It returns the value of the fiber-local variable if a value is assigned.
>> th.fetch(:cat)
=> "meow"

2. It raises a KeyError if it does not have a fiber-local variable of the same name.

>> th.fetch(:dog)
Traceback (most recent call last):
3: from /home/atul/.rvm/rubies/ruby-2.5.0/bin/irb:11:in `<main>'
2: from (irb):7
1: from (irb):7:in `fetch'
KeyError (key not found: dog)

The method raises an ArgumentError when one or two arguments are not passed.

>> th.fetch
Traceback (most recent call last):
3: from /home/atul/.rvm/rubies/ruby-2.5.0/bin/irb:11:in `<main>'
2: from (irb):8
1: from (irb):8:in `fetch'
ArgumentError (wrong number of arguments (given 0, expected 1..2))
>> th.fetch(1, 2, 3)
Traceback (most recent call last):
3: from /home/atul/.rvm/rubies/ruby-2.5.0/bin/irb:11:in `<main>'
2: from (irb):9
1: from (irb):9:in `fetch'
ArgumentError (wrong number of arguments (given 3, expected 1..2))

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store