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
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It only takes a minute to sign up.
Sign up to join this communityI 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
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.
object.to_s
in that case.
\$\endgroup\$
– sepp2k
Feb 22 '11 at 18:31
I've read in here(act_as_good_style) (search for .nil?
first occurrence) that you should not check for .nil?
unless you really want to check that, while if you want to know if the object is valued you should go for something like that
value = object ? object.to_s : ''
That by the way fits very well with my policy standard behavior first(exception for very short code first when else statement too long).
value = object.to_s
will do the exact same thing anyway.
\$\endgroup\$
– sepp2k
Jan 26 '11 at 11:03
object === false
.
\$\endgroup\$
– Gareth
Jan 26 '11 at 23:00
I would do:
v = object.to_s
nil.to_s returns "".
Remember nil is also an object in ruby.
In your specific case, using object.to_s
, you don't actually need to check for nil
at all since ruby handles this for you. If the object is nil
it will return an empty string.
Evidence from the irb:
object = nil # => nil
object.to_s # => ""
object = Object.new # => #<Object:0x10132e220>
object.to_s # => "#<Object:0x10132e220>"
I would do this, personally:
value = object unless onject.nil?
This seems a little more expressive to me. Its something I wish we could do in C++, instead of using the ternary operator.
value
right after those statements, there is no difference. You just need something thatresponds_to?
to_s
\$\endgroup\$ – Pablo Fernandez Jan 26 '11 at 23:33