B4ec694f9d955bee753559037aa1805a

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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 !

1e8f141e7857d397d8020ed3b759e88a

Maciej Piechotka

August 15, 2008, August 15, 2008 08:47, permalink

1 rating. Login to rate!

May be something like that:

1
2
3
4
5
6
7
8
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
A8d3f35baafdaea851914b17dae9e1fc

Adam

August 15, 2008, August 15, 2008 13:23, permalink

1 rating. Login to rate!
1
2
3
4
5
6
7
8
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
F288a8afe5302a16a366d5e9d34f2fec

Joe Grossberg

August 15, 2008, August 15, 2008 13:35, permalink

1 rating. Login to rate!

EDIT: Maciej's refactoring is better than mine (above). I didn't know Enumerable#each_cons existed -- very cool! :)

1
2
3
4
5
6
7
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
B4ec694f9d955bee753559037aa1805a

nathan

August 15, 2008, August 15, 2008 14:12, permalink

No rating. Login to rate!

Awesome, thanks guys. Both examples worked like a charm!

56ee28134dd0776825445e3551979b14

Sporkmonger

September 5, 2008, September 05, 2008 19:38, permalink

No rating. Login to rate!

I'd recommend using FasterCSV instead of the default CSV library. As the name suggests, it's faster. :-)

Your refactoring





Format Copy from initial code

or Cancel