HiveBrain v1.2.0
Get Started
← Back to all entries
patternrubyModerate

Avoiding null in variable assignment

Submitted by: @import:stackexchange-codereview··
0
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?

value = object.to_s


or this

value = object.nil? ? "" : object

Solution

If 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.