Reputation: 13
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?
Upvotes: 0
Views: 85
Reputation: 2869
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"
Upvotes: 0
Reputation: 230296
I'd probably write it like this:
a = params[:smth].to_s
a = 'foo2' if a == 'foo'
Upvotes: 7