3

I currently have a single column CSV file such as: ["firstname lastname", "firstname lastname", ...].

I would like to create a CSV file such as ["f.lastname", "f.lastname"...]; f being the first letter of the firstname.

Any idea how I should do that ?

update

Ok well, I feel that I am close thanks to you guys, here's what I got so far :

  require 'csv'
  filename = CSV.read("mails.csv")
  mails = []
  CSV.foreach(filename) do |col|
   mails << filename.map { |n| n.sub(/\A(\w)\w* (\w+)\z/, '\1. \2') }
  end
  puts mails.to_s

But I still get an error.

update2

Ok this works just fine :

require 'csv'
mails = []
CSV.foreach('mails.csv', :headers => false) do |row|
  mails << row.map(&:split).map{|f,l| "#{f[0]}.#{l}@mail.com" }
end
File.open("mails_final.csv", 'w') {|f| f.puts mails }
puts mails.to_s 

Thanks a lot to all of you ;)

2
  • 1
    What error do you get? Commented Apr 18, 2014 at 11:24
  • /System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/csv.rb:1254:in `initialize': no implicit conversion of Array into String (TypeError) Commented Apr 18, 2014 at 12:26

3 Answers 3

4

A solution without using regular expression:

ary = ["firstname lastname", "firstname lastname"]
ary.map(&:split).map{|f, l| "#{f[0]}. #{l}" }
#=> ["f. lastname", "f. lastname"]
Sign up to request clarification or add additional context in comments.

1 Comment

Okay it works, just one thing, how do I delete the space between f. and lastname for example ? Update : Nevermind, I managed to do it ;) Thanks a lot
1
ary = ["firstname lastname", "firstname lastname"]
ary.map{|a| e=a.split(" "); e[0][0]+"."+e[1]}
#=> ["f.lastname", "f.lastname"]

You need to modify your this following code:--

CSV.foreach(filename) do |col|
  mails << filename.map { |n| n.sub(/\A(\w)\w* (\w+)\z/, '\1. \2') }
end

to match something like the following:--

CSV.foreach(path_to_csv_file/mails.csv, headers: true/false) do |row|
  # row is kind _of CSV::Row, do not use filename.map => causing error
  mails << row.to_hash.map { |n| n.sub(/\A(\w)\w* (\w+)\z/, '\1. \2') }
end

1 Comment

Hm I get this : test.rb:5:in block in <main>': undefined method to_hash' for ["Able Parris"]:Array (NoMethodError)
0

I would do that way:

array = ["firstname lastname", "firstname lastname"]
array.map { |n| "#{n[0]}.#{n.split[1]}" }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.