Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I raise an exception if an evaluation returns nil in Ruby?

Tags:

ruby

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])
like image 701
mydoghasworms Avatar asked Dec 24 '22 07:12

mydoghasworms


2 Answers

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.

like image 158
matthewd Avatar answered May 08 '23 11:05

matthewd


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]
like image 42
iGian Avatar answered May 08 '23 10:05

iGian