def fix_send_to_array(array)
a = array.split(',')
names = []
emails = []
a.each{|x| names << x unless x.include?('@') }
a.each{|x| emails << x unless !x.include?('@') }
index = 0
recipients = Array.new
names.each{|d|
puts d
recipients[index] = {'name' => names[index],'email' => emails[index] }
index += 1
}
recipients
end
Refactorings
No refactoring yet !
Maciej Piechotka
August 15, 2008, August 15, 2008 08:47, permalink
May be something like that:
require 'enumerator'
def fix_send_to_array(array)
recipients = []
array.split(',').each_cons(2) do |arr|
recipients << {:name => arr[0], :email => arr[1]}
end
end
Adam
August 15, 2008, August 15, 2008 13:23, permalink
require "csv"
require "enumerator"
def fix_send_to_array(recipients)
CSV.parse_line(recipients).enum_slice(2).map do |name,email|
{ "name" => name, "email" => email }
end
end
Joe Grossberg
August 15, 2008, August 15, 2008 13:35, permalink
EDIT: Maciej's refactoring is better than mine (above). I didn't know Enumerable#each_cons existed -- very cool! :)
def email_list_to_array(list)
people = []
list.split(',').each_with_index{|x,i|
(i % 2).zero? ? people[i/2] = {:name => x} : people[i/2][:email] = x
}
people
end
nathan
August 15, 2008, August 15, 2008 14:12, permalink
Awesome, thanks guys. Both examples worked like a charm!
Sporkmonger
September 5, 2008, September 05, 2008 19:38, permalink
I'd recommend using FasterCSV instead of the default CSV library. As the name suggests, it's faster. :-)
Hello all,
I am trying to find a better way of converting:
"Nathan,nc@ch.com,Connie,cf@hotmail.com,Mike,mh@ch.com"
INTO
[{"name"=>"Nathan", "email"=>"nc@ch.com"}, {"name"=>"Connie", "email"=>"cf@hotmail.com"}, {"name"=>"Mike", "email"=>"mh@ch.com"}]
The following works, but leaves me wonder if there is a better way.