简体   繁体   中英

Refactor ruby condition with params

I'd like to know if there is a simpler way to do this condition in ruby

My Condition :

a = params[:smth].to_s == 'foo' ? 'foo2' : params[:smth].to_s

The problem of that condition, that reek throw warning of using params[:smth] 2 times, there is one possibility to assign params[:smth] to variable, but maybe you know smarter way?

I'd probably write it like this:

a = params[:smth].to_s
a = 'foo2' if a == 'foo'

You can use lambda for this. But the set varialbe before is the best way.

like this:

p =->(s){s == 'foo' ? 'foo2' : s}

params = {smth: 'foo'}
a = p.(params[:smth].to_s)
# => "foo2"

params = {smth: 'bar'}
a = p.(params[:smth].to_s)
# => "bar"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM