Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialize variables in Ruby - best practice

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?

like image 744
leflic Avatar asked Feb 21 '26 00:02

leflic


1 Answers

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.

like image 193
Eric Duminil Avatar answered Feb 23 '26 13:02

Eric Duminil