Testing express

Testing express

Wednesday, November 16, 2011

Convert a string to a list

Ruby is one of my favourite languages. Its because of its ease of use. I always had  a problem of converting a long string as a list to put in excel. Before I knew any scripting I used to do it manually by copy pasting each word of string in excel. This was not so frequent, so I did not pay much attention but this situation gave me some motivation. I thought of finiding a solution using ruby. Its damn easy and a permanent solution. you can do it only with very few lines of code

fruits = "apple,mango,pear,water melon,guava,black and blue (berries)"
list = [fruits]
list.each do|ps|
  a = ps.split(/,/)
  puts a
end

Output is:
apple
mango
pear
water melon
guava
black and blue (berries)

Now I can easily put it in an excel

Explanation:

I am storing the string in a string variable, then passing it to an array list. Then I iterate over the array and split when there is a ',' and then store each element in variable 'a' and print it on screen.

I know this can be done in many other ways, I would love to see that. feel free if you have more better solutions. My intention here is to solve my problem and get some hands on with ruby.

No comments:

Post a Comment