I need to make my code more compact. I have the following code:
params[:investor][:profit] = params[:investor][:profit].nil? ? nil : params[:investor][:profit].gsub(/\D/, '')
Basically what it does – it formats profit value from params to contain only digits, and if it was nil – just keep it nil…Is there any way to make it shorter.
If the value of
params[:investor][:profit]is nil, this will evaluate tonil && .... Since nil is false, it will stay at nil, otherwise do thegsub.I think it is heads up with the
trysolution mentioned in another solution. Choosing one over the other comes down to personal taste. I like the&&=solution because it’s ruby instead of a rails convenience method and you do not need to “encrypt” what you really want to do in the try method’s parameters.