开发者

ruby: how avoid if-then-else when doing case-insensitive comparison that handles nil too

I frequently find myself having to do an extra nil check (to avoid throwing an 'undefined for nil' error) that I'm pretty sure is unnecessary.

In one common example, when looking at optional url params, e.g. which might or might not exist, I like them to be case insensitive (if they exist).

for example one of my controller methods allows (doesn't require) 开发者_如何转开发&showdate=true and I like to make it user friendly by not caring about true vs TRUE vs True.

I could just say

@showdate = params[:showdate] == "true"

but that assumes lower case.

If I do this:

@showdate = params[:showdate].lower == "true"

it of course throws an unwanted error if showdate is missing from the url becasue nil.lower throws an error.

So I end up doing something like this LOTS of time in my code:

if params[:showdate] 
  @showdate = params[:showdate].lower == "true"
else
  @showdate = false (or maybe nil)

I know there's a Better Way, just don't know what it is. Any help would be appreciated.


@showdate = params[:showdate].to_s.downcase == "true"


Rails?

@showdate = params[:showdate].try(:downcase) == "true"

or

@showdate = !!params[:showdate] && params[:showdate].downcase == "true"


You could do it this way:

@showdata = (params[:showdate] || '').downcase == 'true'
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜