Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access Thor Option Hash

Tags:

ruby

thor

I want to merge a value into a Thor option hash.

If I just use merge I get an error, HashWithIndifferentAccess

I have read the documentation but I have difficulties to understand how to get it to work. I guess I hope this question will help me to both find an answer on the question how to merge a value into this kind of hash and understand how to read documentation.

p options.inspect 
#=> "{\"ruby\"=>\"/Users/work/.rbenv/versions/1.9.2-p290/bin/ruby\"}"
p options.merge!(:a => true)
#=> hash_with_indifferent_access.rb:26:in `[]=': can't modify frozen hash (RuntimeError)
like image 786
bandola Avatar asked May 26 '26 10:05

bandola


1 Answers

The hash is frozen:

"Prevents further modifications to obj. A RuntimeError will be raised if modification is attempted. There is no way to unfreeze a frozen object."

You can copy options to a new hash (will be unfrozen) and modifying that instead.

new_options = options.dup
options = new_options
options.merge!(:a => "this will work now")

Or if you want it to be even briefer:

options=options.dup
options.merge!(:a => "this will work now")

The Thor library returns a frozen hash by default, so another option would be to modify the library to return unfrozen hashes, but I think the first solution is good enough.

Below is a link to the source code for Thor's parse function, you'll notice it freezes the "assigns" return hash prior to actually returning it (go to the bottom of the page, and under (Object) parse(args), click 'View Source'. The freezing is on line 83 of the source snippet.)

http://rubydoc.info/github/wycats/thor/master/Thor/Options

like image 160
Roadmaster Avatar answered May 30 '26 16:05

Roadmaster



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!