将多个变量合并为一个字符串并添加逗号

时间:2017-12-20 08:06:11

标签: arrays ruby string

我有多个字符串:

address_1 = '226'
address_2 = 'Virginia Ave'
address_city = 'Trenton'
address_state = 'NJ'
address_country = 'US'
address_postal_code = '08610'

我正在尝试将它们组合成一个字符串,用逗号分隔,如下所示:

"226 Virginia Ave, Trenton, NJ, 08610, US"

如何在字符串中组合我的变量,使用逗号分隔它们,如果缺少任何变量,那么不显示额外的逗号?

我这样做了:

(address_1.to_s + ' ' + address_2.to_s + ' ' + address_city.to_s + ' ' + address_state.to_s + ' ' + address_postal_code.to_s + ' '  + address_country.to_s).squish

这样输出如下:

"226 Virginia Ave Trenton NJ 08610 US"

这是因为我正在添加空格+ ' ' +。如果我执行+ ', ' +,如果address_中的任何一个nil为空或者为空,它仍会显示额外的,,并且地址最终会如下所示:

"226 Virginia Ave, , , 08610, US"

2 个答案:

答案 0 :(得分:2)

address_1 = '226'
address_2 = 'Virginia Ave'
address_city = 'Trenton'
address_state = 'NJ'
address_country = 'US'
address_postal_code = '08610'

["#{address_1} #{address_2}", address_city, address_state, address_country, address_postal_code].map{|line| line.to_s.strip}.select{|line| !line.empty?}.join(', ')

这会将所有地址元素放在一个数组中,map将所有行更改为条带化字符串,然后选择非空行,然后使用逗号和空格连接。

第一个元素是address_1和地址2的组合,以避免在门牌号后面有逗号。

答案 1 :(得分:1)

尝试使用数组紧凑。这可以解决您的问题。

address_arr = [address_1, address_2, address_city, address_state, address_country, address_postal_code]
no_empty_address = address_arr.reject{ |c| c.empty? }
no_empty_address.compact.join(', ')