Another way to write: if some_variable && some_valiable.size == 2

In Ruby and RoR, I often find that an object exists, that is, whether the properties of the object meet certain criteria. For instance:

if params[:id] && params[:id].size == 40
  ...do stuff
end

Is there a more efficient way to do this? Sort of:

if params[:id].size == 40 rescue false

but not using salvation?

+3
source share
3 answers

With Rails 2.3, you can use the # method of object #:

if params[:id].try(:size) == 40
  # do stuff
end

try will return nil when nil is called (with any arguments). Hope this makes sense.

+13
source

Try using andand gem:

require 'andand'

if params.andand.size == 40
  ...do stuff
end
0
source

You can do this without additional gems.

if params[:id].to_a.size == 40
    ... do stuff
end
0
source

Source: https://habr.com/ru/post/1727642/


All Articles