编辑阵列的单元我写了下面的:如何从功能红宝石
def clean(row)
row.each.with_index do |cell, index|
next if cell.nil?
# Replace all spaces and non-breakable spaces by regular spaces
cell.gsub!(/\A\p{Space}*/, ' ')
# Remove leading and trailing spaces
cell.strip!
# Homogenize empty values by setting everything to `nil`
row[index] = nil if cell.empty?
end
end
块的最后一行是想要什么,我请你注意。我想知道这是否是真正改变原始行相关单元格值的唯一方法?如果没有,是否有更聪明的方法来做到这一点?
编辑:
下面是使用@ascar答案的最终版本:
def clean(row)
row.map! do |cell|
if cell.nil? || cell.empty?
nil
else
cell.gsub!(/\A\p{Space}*/, ' ')
cell.strip!
cell.empty? ? nil : cell
end
end
end
我没有看到任何错误的代码。但是,如果您使用的是ActiveSupport,则可以使用[String#blank?](http://guides.rubyonrails.org/active_support_core_extensions.html#blank-questionmark-and-present-questionmark),而不是自己转换并检查空白处,它可以清理代码。 – 2014-09-22 16:31:02
你能否提供你的'行'对象的样本? – 2014-09-22 16:39:47
@Adrien Giboire链接!方法是危险的。例如GSUB!如果没有被替换,将返回nil而不是原始字符串。 – dfherr 2014-09-24 11:16:31