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
I want to get empty string or the string value of the object Which code you will use and why?
or this
|
||||
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 |
|||||||||||||
|
I've read in here(act_as_good_style) (search for
That by the way fits very well with my policy standard behavior first(exception for very short code first when else statement too long). |
|||||||||||||
|
I would do:
nil.to_s returns "". Remember nil is also an object in ruby. |
|||
|
In your specific case, using Evidence from the irb:
|
|||
|
I would do this, personally:
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
– Pablo Fernandez Jan 26 '11 at 23:33