Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Ruby safe operator with greater than

Tags:

ruby

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?

like image 573
stephenmurdoch Avatar asked Mar 06 '19 18:03

stephenmurdoch


Video Answer


2 Answers

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
like image 44
tadman Avatar answered Sep 28 '22 08:09

tadman


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.

like image 108
Andrew Schwartz Avatar answered Sep 28 '22 08:09

Andrew Schwartz