operators - how to use ruby to assign a default if a value is nil? -


i have following default 5 if there not value json_element['limit']:

json_element['limit'] = 500 limit           ||=  json_element['limit'].to_i limit           ||=  5 

this current implementation, seems 1 line long.

as amndan says, idea here order things in order of precedence, highest lowest, left right, speaking:

def do_thing(limit_override)   limit ||= limit_override || input || default end 

in case you're testing hash property , converting integer, have options:

limit ||= json_element['limit'] ? json_element['limit'].to_i : 5 

or to_i whatever if it's ever less efficient:

limit ||= (json_element['limit'] || 5).to_i 

Comments

Popular posts from this blog

php - Vagrant up error - Uncaught Reflection Exception: Class DOMDocument does not exist -

vue.js - Create hooks for automated testing -

.htaccess - ERR_TOO_MANY_REDIRECTS htaccess -