Take the 2-minute tour ×

Hey guys I'm writing a ruby program that reads a database of food items and recipes that is in CSV format, and writes it back to a file. I'm having issues writing to a CSV file correctly

I want to write an objects attributes to a CSV file

csv_text = CSV.open("FoodDB1.txt","w") do |i|
    @@dataList.each do |j|
        if j.get_type == "b"
            i << [j.name,j.get_type,j.cal]
        elsif j.get_type == "r"
            i << [j.name,j.get_type,j.print_bFood]

I have two types of objects, basic food and a recipe. Both are stored in the dataList array. I check each object for its type, if it's a basic food, writing it is easy since it is just three simple fields. If it is a recipe, I write the name,type,and the basic foods that make up that recipe.

The issue I'm having is at this line

i << [j.name,j.get_type,j.print_bFood]

So it prints out the name of the recipe, the type(whether its a basic food or a recipe) and then finally the list of foods in the recipe. That is where I'm having issues.

bFood is an array of basic foods that is stored in the object, and I'm having trouble adding it to the CSV row. I tried making a method(which is print_bFood) that returns a string of the combined array using .join(","), but because of the comma in the string, when CSV writes it to a file it is wrapped in quotes

"PB&J Sandwich,r,"Jelly,Peanut butter,Bread slice, Bread slice""

I want it to look like this

"PB&J Sandwich,r,Jelly,Peanut butter,Bread slice, Bread slice"

Any ideas on what can help. I've looked for ways to do this and I just can't think of anything anymore.

One idea I had was if I had the ability to just add on to a row, I could iterate through the bFood array and add each one to the row, but I haven't found any functionality that can do that.

share|improve this question

1 Answer 1

up vote 0 down vote accepted

If I read this correctly you should just need...

i << [j.name, j.get_type, j.bFood].flatten
share|improve this answer
Ah thank you so much! I don't understand why I wasn't able to find this. So now that I know to flatten an array, I just made a method that made a new array of just the basic food object names, and put that in the cvs write out and it works great. Thanks! –  lettuceman44 Feb 1 '13 at 21:44

Your Answer


