开发者

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

In Ruby & in RoR I oft find myself testing whether an object exists, then whether an object's properties match some criteria. Like so:

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

Is there a more efficient way to do this? Something like:

if params[:id]开发者_运维百科.size == 40 rescue false

but without using the rescue?


With Rails 2.3 you can use Object#try method:

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

try will return nil when called on nil (with any arguments). Hope that makes sense.


You can do it witout additional gems.

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


Try the andand gem:

require 'andand'

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜