英文:
Add comma in array first element in Rails
问题
我有一个在Ruby on Rails中的数组。
"Atlanta, GA 30114"
英文:
I have an array in Ruby on Rails.
[city, state, zip].reject(&:blank?).join(' ')
I want to add comma after first element of an array i.e city
"Atlanta, GA 30114"
答案1
得分: 1
Rails 6.1 引入了 Enumerable#compact_blank
。您可以使用它来替代 reject(&:blank?)
。
如果只需要在城市后面添加逗号,只需在城市后面添加逗号(如果城市存在)。
def format_city(city, state, zip)
city_with_comma = "#{city}," if city.present?
[city_with_comma, state, zip].compact_blank.join(" ")
end
format_city(nil, "GA", "30114")
# => "GA 30114"
format_city("Atlanta", "GA", "30114")
# => "Atlanta, GA 30114"
英文:
Rails 6.1 introduced Enumerable#compact_blank
. You can use it instead of reject(&:blank?)
If you need add comma only after the city, just add comma to the city if it is present
def format_city(city, state, zip)
city_with_comma = "#{city}," if city.present?
[city_with_comma, state, zip].compact_blank.join(" ")
end
format_city(nil, "GA", "30114")
# => "GA 30114"
format_city("Atlanta", "GA", "30114")
# => "Atlanta, GA 30114"
答案2
得分: 0
在Ruby on Rails中,在数组的第一个元素后添加逗号:
array = ['Atlanta', 'GA', '30114']
result = [array[0], array[1..-1].reject(&:blank?).join(' ')].join(', ')
puts result
reject(&:blank?)
用于确保从结果数组中移除任何空白或空元素。
join(', ')
将数组元素组合成一个以逗号和空格分隔的字符串。
result
变量将包含所需的输出:"Atlanta, GA 30114",在城市名称后面有一个逗号。
英文:
To add a comma after the first element of an array in Ruby on Rails:
result = [array[0], array[1..-1].reject(&:blank?).join(' ')].join(', ')
puts result
reject(&:blank?)
Ensures that any blank or empty elements are removed from the resulting array.
join(', ')
combines the elements of the array into a string, separated by a comma and space
result
variable will hold the desired output: "Atlanta, GA 30114", with a comma after the city name.
Interesting fact:
blank?
Is commonly used in Ruby on Rails instead of empty?
which is commonly used in default Ruby
答案3
得分: 0
"有很多方法可以做到这一点...这里是另一种方法..."
city,state,zip = ["Atlanta","GA","30114"]
[(city+"," if city),state,zip].compact.join(" ") => "Atlanta, GA 30114"
当城市为空时:
city,state,zip = [nil,"GA","30114"]
[(city+"," if city),state,zip].compact.join(" ") => "GA 30114"
英文:
lots of ways to do it... here's another...
city,state,zip = ["Atlanta","GA","30114"]
[(city+"," if city),state,zip].compact.join(" ") => "Atlanta, GA 30114"
when city is blank:
city,state,zip = [nil,"GA","30114"]
[(city+"," if city),state,zip].compact.join(" ") => "GA 30114"
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论