简体   繁体   中英

Access Thor Option Hash

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)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM