Martin Klepsch
Martin Klepsch

Reputation: 1915

Code Beautification: Concatenating Multiple Vars and Strings in Ruby

self.homePostalAddress = self.mozillaHomeStreet + "$" + self.mozillaHomeLocalityName + "$" + self.mozillaHomePostalCode + "$$" + self.mozillaHomeCountryName

I have this line of code and I'd like to split it into multiple rows as it's becoming too long.

I tried other variants with #{} but was not able to achive the desired result.

Upvotes: 0

Views: 177

Answers (2)

Yossi
Yossi

Reputation: 12100

Edited

Following Martin correction that '$$' is not a typo.

Use #join method of Array.

homePostalAddress = [
  '$', mozillaHomeStreet, 
  '$', mozillaHomeLocalityName, 
  '$', mozillaHomePostalCode,
  '$$', mozillaHomeCountryName
].join

Upvotes: 1

Aliaksei Kliuchnikau
Aliaksei Kliuchnikau

Reputation: 13719

You can try to do this using String#% format method:

homePostalAddress = "%s$%s$%s$$%s" % [mozillaHomeStreet, mozillaHomeLocalityName,
                                     mozillaHomePostalCode, mozillaHomeCountryName] 

(You don't need to use self. because these methods will be called on self implicitly).

With string interpolation (#{}) this code will look like this:

 homePostalAddress = "#{mozillaHomeStreet}$#{mozillaHomeLocalityName}$" + 
                     "#{mozillaHomePostalCode}$$#{mozillaHomeCountryName}"

Upvotes: 3

Related Questions