I'm learning Ruby and I've got a question regarding best practice. If I want to initialize a new, empty string, what method is best:
variable = ""
variable = String.new
variable = String("")
variable = String(nil)
Is there any difference?
variable = ""
or
variable = ''
Would be the most common.
Now comes the important question, why do you need it?
Ruby newcomers often write some code like :
words = ['abc', 'def', 'ghi']
variable = ''
for word in words do
variable += word
end
puts variable
before learning that they could just use :
puts words.join
Taking a look at the available Array and String methods might help you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With