我有一组事件对象.每个事件都有一个名为location的哈希,其中包含名称,地址,州,城市,邮政编码等密钥.但是并非所有位置都有这些键.我只想显示键的值,如果它们在那里.这是我的代码
@events.each do |event|
if !event.location.empty?
puts "Location: #{event.location[:name]}, #{event.location[:address]}, #{event.location[:city]}, #{event.location[:state]}, #{event.location[:zipcode]}"
end
end
Run Code Online (Sandbox Code Playgroud)
如果我有一个完整的地址,这工作正常.但是,如果我只有它所显示的位置的名称
Location: Central Park, , , ,
Run Code Online (Sandbox Code Playgroud)
我怎样才能摆脱那些多余的逗号?有时它可能是2或3个尾随逗号.我知道如何摆脱一个,但如果没有设置尾随逗号的数量,我不知道该怎么做.希望将位置信息显示在一行上.
任何帮助,将不胜感激.
我会做这样的事情:
@events.each do |event|
values = event.location.values_at(:name, :address, :city, :state, :zipcode).compact
puts "Location: #{values.join(', ')}" unless values.empty?
end
Run Code Online (Sandbox Code Playgroud)
或者您可能想要为您的Event班级添加方法.
def stringified_location
values = location.values_at(:name, :address, :city, :state, :zipcode).compact
values.join(', ') unless values.empty?
end
Run Code Online (Sandbox Code Playgroud)
并称之为:
@events.each do |event|
stringified_location = event.stringified_location
puts "Location: #{stringified_location}") if stringified_location
end
Run Code Online (Sandbox Code Playgroud)