if false
params[:code] = if false
'N'
else
'Y'
end
This code is just :
params[:code] = 'Y'
No if
, not but : false
is well, always false
, so there's no way N
can be reached. That's the reason rubocop is complaining.
Modified code
I guess you meant to write :
params[:code] = if params[:code] == false
'N'
else
'Y'
end
It's not rubyish at all, but at least it looks like your code and does what you expect it to.
To test it :
params = {code: false}
params[:code] = if params[:code] == false
'N'
else
'Y'
end
p params
# {:code=>"N"}
Warning!
If your params
values are Strings (as they often are), you'll have to test against Strings :
params[:code] = if params[:code] == "false"
'N'
else
'Y'
end
With a ternary :
params[:code] = params[:code] == "false" ? 'N' : 'Y'
Or a hash :
params[:code] = {'true' => 'Y', 'false' => 'N'}[params[:code]]
If you have a fuzzy input (e.g. true
or "true"
or "True"
or "yes"
), you could use Rails built-in methods to convert to boolean :
code = ActiveRecord::Type::Boolean.new.type_cast_from_database(params[:code]) # For Rails 4.2
params[:code] = code ? 'Y' : 'N'