I'm trying to figure out how to use Ruby's safe operator in the following scenario:
if attribute_value && attribute_value.length > 255
The following does not work if the attribute_value is nil:
if attribute_value&.length > 255
# NoMethodError: undefined method `>' for nil:NilClass
I get why, but what I'd like to know is how to I get round this. The following works, but it's ugly as hell:
if attribute_value&.(length > 255)
What's the recommended way of doing this? I guess I could do the following:
if attribute_value&.length.to_i > 255
That's not so bad for this situation. Anything else?
This sort of thing depends on what kind of missing values you're trying to accommodate and if failing to define it is the same as being within bounds, or outside of.
Your approach of:
attribute_value&.length.to_i > 255
Seems reasonable enough so long as nil
means "not outside of bounds".
Often I handle this with guard conditions like:
return unless attribute_value
if attribute_value.length > 255
# ... Handle condition
end
As a direct answer to the question asked, you can use the safe navigation operator directly since x > y
is really just calling the >
method on the object x. That is, x > y
is the same as x.>(y)
or x.send(:>, y)
Therefore, you can use x&.> y
. Or, in your situation, attribute_value&.length&.> 255
Personally, I'd prefer attribute_value && attribute_value.length > 255
, but maybe that's just me.
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