将数组动态保存到哈希中的最佳方法是什么?

时间:2014-03-08 19:51:26

标签: ruby sinatra ruby-datamapper

DataMapper将其错误保存为Validate :: ValidationErrors对象。我想将这些错误转换为数组并保存由正在创建的新项目的名称(类别)索引的错误。我是Ruby的新手,正在寻找关于重构错误如何在返回值中保存的一些指导。任何建议都会受到欢迎。

具体来说,我觉得这些线看起来不是最佳:

....

# save error set as hash
data[:errors][clean] = Hash.new unless not data[:errors][clean].nil?
data[:errors][clean] = cat.errors.to_a.join(', ')

....

这是整个方法

def self.createMany( input )

  # convert everything to lowercase
  categories = input.downcase

  data = {:errors => Hash.new, :success => Array.new }

  # convert input into array
  categories.split(',').each do |c|

    # remove leading and trailing white spaces
    clean = c.strip 

    # init new category
    cat = Category.new(:name => clean)

    # save cat
    if cat.save
      data[:success] << "#{clean} created"
    else
      # save error set as hash
     data[:errors][clean] = Hash.new unless not data[:errors][clean].nil?
     data[:errors][clean] = cat.errors.to_a.join(', ')
    end
  end

  data

end

1 个答案:

答案 0 :(得分:1)

不需要这一行

data[:errors][clean] = Hash.new unless not data[:errors][clean].nil?

您可以执行以下示例

> data = {:errors => {}, :success => []}
# => {:errors=>{}, :success=>[]} 
> data[:errors]["cat1"] = "error 1"
# => "error 1" 
> data[:errors]["cat2"] = "error 2"
# => "error 2" 
> data
# => {:errors=>{"cat1"=>"error 1", "cat2"=>"error 2"}, :success=>[]}