1

I am currently using Ruby for a CSV file and I am trying to print a column data given a condition.

Severity  Level
Least       1
Average     2
Normal      3
High        4
Severe      5

require "csv"
CSV.foreach('csvread.csv', :headers=>true) do |row|
  if (row[1] == 2) 
    puts row.inspect
  end
end

How do I select the Level column and print out the severity?

CSV file structure:

Severity;Level
Least;1
Average;2
Normal;3
High;4
Severe;5

1 Answer 1

2

You can access to Security and Level, and any other value you define in your header as object['header'].

In this case the object is each row for the iteration, and the values are Severity and Level, so:

require 'csv'

file = '/path_to_data/data.csv'
CSV.foreach(file, headers: true, col_sep: ';') do |row|
  p [row['Severity'], row['Level']]
end

# ["Least", "1"]
# ["Average", "2"]
# ["Normal", "3"]
# ["High", "4"]
# ["Severe", "5"]
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.