Ruby 2.5 adds Thread#fetch method

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))