views:

47

answers:

1

Lets say I have a rails application in which code is pasted into the content text box like the following.

Pasted Code

Person name
Person name
Person name
Person name

It is put into the database with the proper new lines after each line according to my server log.

What I want to do is in the show action I want to output this text after removing any blank spaces between names and remove any double names and put them in alphabetical order.

I also want to add an html option tag around them.

I have already written a program in Java to do this using sets. I was wondering how to approach this in rails. I would assume the code to do this would go in the controller.

My second question was in the index action. It shows all the pasted items. How can I only show a snippet of what was actually pasted. Lets say 20 characters long? Thanks!

+1  A: 

removing any blank spaces between names

have no idea what 'blank spaces between' means, but I assume you want to remove 'blank lines':

lines = code.split(/\n\r?/).reject { |l| l.strip.empty? }

remove any double names

lines = lines.uniq # or uniq!

put them in alphabetical order

lines = lines.sort # or sort!

add an html option tag around them

options_str = lines.map { |l| "<option value='#{l}'>#{l}</option>" }.join('\n') # Do not forget to escape html

Or if you want it shorter:

code.split(/\n\r?/).reject { |l| l.strip.empty? }.uniq.sort.map do |l|
  "<option value='#{l}'>#{l}</option>"
end.join('\n')

That should give you a tip.

The most important thing for you would probably be having String, Array and Enumerable documentation in front of you.

Dmytrii Nagirniak