I want to do something along the lines of this:
lookup_value = :f
dict = {a: 20, b: 30, c: 40}
res = dict[lookup_value] | raise 'not found'
As in the above example, if the key is not found in the dictionary, I want to raise an error. I could just have an additional line which says raise 'not found' unless res
, but I really want to use the lookup in an expression:
output = 'prefix' + (dict[lookup_value] | raise 'not found')
The problem is that using raise
in this way is not valid syntax. I am looking for a way that I can raise an error in an expression if the lookup of the value in the hash fails without having to declare additional variables or do a check beforehand.
The following is valid syntax and will throw an exception if the value is not found, but returns nil when a value is found:
res = (raise 'not found' unless dict[lookup_value])
dict.fetch(lookup_value)
is like dict[lookup_value]
, but will raise if the key was missing.
You can also do approximately what you have in the question, with a couple of tweaks: dict[lookup_value] || raise('not found')
-- that gives you control of the exception.
This should fix the nil return when a value is found.
Changing this:
res = (raise 'not found' unless dict[lookup_value])
into this:
raise 'not found' unless res = dict[lookup_value]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With