Ruby时为零或空字符串

Jav*_*cia 2 ruby ruby-on-rails

我有RoR应用程序,我想更改我的代码的一些行更优雅.

foo = params[:customer][:language].nil? or params[:customer][:language].empty? ? 'es' : params[:customer][:language]
Run Code Online (Sandbox Code Playgroud)

我试着用

foo = params[:customer][:language] || 'es'
Run Code Online (Sandbox Code Playgroud)

但它完全不一样.

提前致谢.

Mar*_*pka 7

您可以使用activesupport的Object#presence方法,如下所示:

foo = params[:customer][:language].presence || 'es'
Run Code Online (Sandbox Code Playgroud)

  • `#Bresent`非常有用.特别是如果你必须链接多个,例如:`city.presence || country.presence || planet.presence`.该行将返回第一个非零或非""结果. (2认同)