如何从ruby中的函数编辑数组的单元格

时间:2014-09-22 16:24:14

标签: ruby

我写了以下内容:

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

1 个答案:

答案 0 :(得分:1)

Array#map!应该做你想做的事情

def clean(row) 
 row.map! do |cell|
   if cell.nil? || cell.empty?
     nil
   else
     cell.gsub(/\A\p{Space}*/, ' ').strip
   end
 end
end

或使用Array#map如果您想要返回新数组而不进行编辑。