user_pruser
user_pruser

Reputation: 450

ruby hash.values is not working with built in method

i tried almost everything but I am feeling cornered.

I have a CSV and reading a line from it:

CSV.foreach(file, quote_char: '"', col_sep: ',', row_sep: :auto, headers: true) { |line|

    newLine = []
    newLine = line.values #undefined method .values
    ...
}

line is aparently hash, because line['column_name'] is working fine and also line.to_a returns ["col","value","col2","value2",...]

please help, thank you!

Upvotes: 1

Views: 227

Answers (3)

Sid
Sid

Reputation: 2943

It is a CSV row which is part array and part hash and doesn't have the .values method available. Use .to_hash first and then you will be able to use .values. (Note that this will remove the field ordering and any duplicate fields)

newLine = line.to_hash.values

Upvotes: 0

peter
peter

Reputation: 42192

It is not a regular hash, it is an instance of CSV::Row, see here for the API

As you can see in the result of the following code the method values isn't there. Your solution of using line['column_name'] is fine. You can get all the fields with the method fields without parameter.

CSV.parse(DATA, :col_sep => ",", :headers => true).each do |row|
    puts row.class
    puts row.methods - Object.methods
end

__END__
kId,kName,kURL
1,Google UK,http://google.co.uk
2,Yahoo UK,http://yahoo.co.uk

Upvotes: 0

floum
floum

Reputation: 1159

You can use #fields on the class CSV::Row

http://ruby-doc.org/stdlib-1.9.3/libdoc/csv/rdoc/CSV/Row.html

Upvotes: 1

Related Questions