1

CSV headers can be converted with header_converters and lambda expressions, as shown in "Using Ruby CSV header converters". However, is there a way to specifically only convert say the first column, and leave the others untouched?

For example, assume my headers are

<random string>, head1, head2, headN

The value of <random string> may change between CSV files, and I'd like to change this header to some predetermined string, so that headers become

time, head1, head2, headN
1
  • It would be better if you supplied an example of the input CSV and the expected output CSV, rather than ask people to go read the other question. Commented Feb 6, 2017 at 21:46

1 Answer 1

6

I did not find this documented in examples, only in the source of csv.rb. Converters receive an optional second argument, field_info. According to the documentation, this is a Struct with the fields index, line, and header:

  • index: The zero-based index of the field in its row.
  • line: The line of the data source this row is from.
  • header: The header for the column, when available.

So as an example, this will convert the first header to "time" and leave others untouched:

CSV.new(f, header_converters: lambda{|h, field_info| field_info.index == 0 ? "time" : h })
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.