在Rails中,在数组的第一个元素前添加逗号。

huangapple go评论63阅读模式
英文:

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"

huangapple
  • 本文由 发表于 2023年5月22日 20:32:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/76306248.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定