... more

With :skip_line working you can now strip off the "unless
row_to_add.empty?" because all (/,,,/) rows will be skipped.

Abinoam Jr.

On Tue, Mar 4, 2014 at 8:08 PM, Abinoam Jr. <abinoam / gmail.com> wrote:
> Hi Arup,
>
> Jes=FAs has guided you to the right way! ;-)
> (I've tested and it worked).
>
> But I would give you some suggestions (not directly related to your quest=
ion).
>
> I think the "right" way to deal with the converters is:
>
> CSV::Converters[:remove_quotes] =3D lambda { |field| field.to_s.tr('"',''=
) }
>
> options =3D { :skip_blanks =3D> true,
>            :quote_char =3D> "\'",
>            :converters =3D> :remove_quotes,
>            :skip_lines =3D> /,,,/
>          }
>
> Your approach only works because the assignment
>
> CSV::Converters[:remove_quotes] =3D lambda do |field|
>              field.to_s.tr('"','')
>            end
>
> returns the lambda itself.
>
> And, as stated at the documentation,
> "A single converter doesn't have to be in an Array."
>
> So, the fragment ...
>            :converters =3D> CSV::Converters[:remove_quotes] =3D lambda do=
 |field|
>              field.to_s.tr('"','')
>            end
>
>
> ... acts exactly the same as
>            :converters =3D> lambda do |field|
>              field.to_s.tr('"','')
>            end
>
> Abinoam Jr.
>
> On Mon, Feb 24, 2014 at 3:40 AM, Jes=FAs Gabriel y Gal=E1n
> <jgabrielygalan / gmail.com> wrote:
>> On Sun, Feb 23, 2014 at 4:30 PM, Arup Rakshit <lists / ruby-forum.com> wro=
te:
>>> Here is a CSV data in one of my file has :
>>>
>>> "DE","Klasse","Deutsch", "x"
>>> "EN","Class","Carpenter",
>>> "DE","Klasse","Mathe",
>>> ,,,
>>>
>>> Code I wrote :
>>>
>>> require 'csv'
>>>
>>> input_file_path =3D File.expand_path('input.csv',File.dirname(__FILE__)=
)
>>> output_file_path =3D File.expand_path('output.csv',File.dirname(__FILE_=
_))
>>>
>>> option =3D { :skip_blanks =3D> true,
>>>            :quote_char =3D> "\'",
>>>            :converters =3D> CSV::Converters[:remove_quotes] =3D lambda =
do
>>> |field|
>>>              field.to_s.tr('"','')
>>>            end
>>>          }
>>>
>>> CSV.open(output_file_path,'w',:force_quotes =3D> true) do |out_row|
>>>   CSV.foreach(input_file_path, option) do |in_row|
>>>     row_to_add =3D in_row.reject(&:empty?)
>>>     out_row.puts row_to_add unless row_to_add.empty? or
>>> row_to_add.last[/^\s+x$/]
>>>   end
>>> end
>>>
>>> **output** ( also expected )
>>>
>>> "EN","Class","Carpenter"
>>> "DE","Klasse","Mathe"
>>>
>>> But my question is -
>>>
>>> How can I skip lines like **,,,** using option **:skip_lines** (
>>> http://www.ruby-doc.org/stdlib-2.0/libdoc/csv/rdoc/CSV.html#method-c-ne=
w)
>>
>> The :skip_lines option receives an object that responds to match (for
>> example a Regex). The lines for which this object returns false are
>> skipped. For example:
>>
>> :skip_lines =3D> /,,,/
>>
>> (untested)
>>
>> Jesus.