0

我有一个如下形式的列表:

"first - http://url.com, second - http://url.net, third - http://url.so"

# i.e. name - url, name - url, name - url
# so I have three name - url pairs

我想获取这个列表并创建三个 Foo 对象(每个都有 name 和 url 属性),所以我想出了这个:

def foo_list=(list)
  self.foos = list.split(",").map { |pair| pair.split(" - ") }.each.map { |attr| Foo.where(name: attr[0].strip, url: attr[1].strip).first_or_create }
end

这工作正常,但它有点冗长。有没有更简单的方法呢?

4

2 回答 2

1

不是一个更好的选择,而是一种更易读的方式

self.foos = list.split(',').map do |pair|
  name, url = pair.split(' - ')
  Foo.where(name: name.strip, url: url.strip).first_or_create
end
于 2013-03-11T08:19:16.110 回答
0

我可能会写成:

self.foos = list.split(",").map { |pair|
  pair.split("-").map(&:strip)
}.map { |name, url|
  Foo.where(name: name, url: url).first_or_create
}

当您可以strip将其作为split('-')

于 2013-03-11T16:33:50.497 回答