stephenmurdoch
stephenmurdoch

Reputation: 34613

Splitting a list twice in Ruby

I've got a list in the following form:

"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

I want to take this list and create three Foo objects (each with name and url attributes), so I've come up with this:

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

This works fine, but its a bit verbose. Is there a simpler way of doing it?

Upvotes: 0

Views: 596

Answers (2)

the Tin Man
the Tin Man

Reputation: 160551

I'd probably write it as:

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

There's no need to strip twice when you can do it as part of the split('-')

Upvotes: 0

jvnill
jvnill

Reputation: 29599

not really a better option but a more readable way

self.foos = list.split(',').map do |pair|
  name, url = pair.split(' - ')
  Foo.where(name: name.strip, url: url.strip).first_or_create
end

Upvotes: 1

Related Questions