ruby - manipulating array: adding number of occurrences to the duplicate elements -


(you welcome change title more appropriate one!)

i got ruby/erb question. have file:

ec2-23-22-59-32, mongoc, i-b8b44, instnum=1, running ec2-54-27-11-46, mongod, i-43f9f, instnum=2, running ec2-78-62-192-20, mongod, i-02fa4, instnum=3, running ec2-24-47-51-23, mongos, i-546c4, instnum=4, running ec2-72-95-64-22, mongos, i-5d634, instnum=5, running ec2-27-22-219-75, mongoc, i-02fa6, instnum=6, running 

and can process file create array this:

irb(main):007:0> open(infile).each { |ln| puts ln.split(',').map(&:strip)[0..1] } ec2-23-22-59-32 mongoc ec2-54-27-11-46 mongod .... .... 

but want occurrence number concatenated "mongo-type" becomes:

ec2-23-22-59-32 mongoc1 ec2-54-27-11-46 mongod1 ec2-78-62-192-20 mongod2 ec2-24-47-51-23 mongos1 ec2-72-95-64-22 mongos2 ec2-27-22-219-75 mongoc2 

the number of each mongo-type not fixed , changes on time. how can that? in advance. cheers!!

quick answer (maybe optimized):

data = 'ec2-23-22-59-32, mongoc, i-b8b44, instnum=1, running ec2-54-27-11-46, mongod, i-43f9f, instnum=2, running ec2-78-62-192-20, mongod, i-02fa4, instnum=3, running ec2-24-47-51-23, mongos, i-546c4, instnum=4, running ec2-72-95-64-22, mongos, i-5d634, instnum=5, running ec2-27-22-219-75, mongoc, i-02fa6, instnum=6, running'  # hash save mongo types strings keys # , number of occurence values mtypes = {} data.lines.each |ln|   # first , second element of given string inst , mtype respectively   inst, mtype = ln.split(',').map(&:strip)[0..1]   # check if mtypes hash has key equ current mtype   # if yes -> add 1 current number of occurence   # if not -> create new key , assign 1 value   # if ? true : false -- ternary operator   mtypes[mtype] = mtypes.has_key?(mtype) ? mtypes[mtype] + 1 : 1   # combine output string (everything in #{ } variables   # #{mtype}#{mtypes[mtype]} means take current value of mtype ,   # place after current number of occurence stored mtypes hash   p "#{inst} : #{mtype}#{mtypes[mtype]}" end 

output:

# "ec2-23-22-59-32 : mongoc1" # "ec2-54-27-11-46 : mongod1" # "ec2-78-62-192-20 : mongod2" # "ec2-24-47-51-23 : mongos1" # "ec2-72-95-64-22 : mongos2" # "ec2-27-22-219-75 : mongoc2" 

quite strightforward think. if don't understand -- let me know.


Comments

Popular posts from this blog

php - Calling a template part from a post -

Firefox SVG shape not printing when it has stroke -

How to mention the localhost in android -