patternrubyModerate
Avoiding null in variable assignment
Viewed 0 times
assignmentnullvariableavoiding
Problem
I want to get empty string or the string value of the object
Which code you will use and why?
or this
Which code you will use and why?
value = object.to_sor this
value = object.nil? ? "" : objectSolution
If
If it can be anything and you want to get a string, your second solution doesn't actually do what you want, since it won't turn the object into a string if it's not nil. To fix that your second solution would become
object is either nil or a string, you can just do value = object || "".If it can be anything and you want to get a string, your second solution doesn't actually do what you want, since it won't turn the object into a string if it's not nil. To fix that your second solution would become
value = object.nil? ? object.to_s : "". Of course since now you're calling to_s in both solutions there is no reason to prefer the second over the first, so I'd go with the first.Context
StackExchange Code Review Q#214, answer score: 12
Revisions (0)
No revisions yet.