1

I figured already out how to work with ar_of_ar, but can't select multiple elements of only the second column.

temp_ary=CSV.read(file, {col_sep->";"})  

the mounted file has the structure:

[Date, value]  
june6;1200.02  
jul6;500.04    
dec06; 3400.07

after having imported, I want to count the values which are greater than 1000. However, the normal adressing I'm used to does not work, thus selecting values 1..3 of column2:

temp_ary[2..3][1]  

only returns the first value?

I'm not sure whatever values I can expect, but I want to count occurring nil, null, 0, space values and so on, which are no real numbers. How can I efficiently do that?

1
  • Please note that there is no such thing as null in Ruby, there is only nil. Commented Mar 16, 2012 at 20:37

1 Answer 1

1

You could do something like this:

require "csv"

def csv
  @csv ||= CSV.read("./test.csv", :col_sep => ';')
end

puts csv.count {|x| x.last.to_i > 1000}

You can pass a "block" to the count method to specify a predicate to count on. See http://www.ruby-doc.org/core-1.9.3/Array.html#method-i-count

Also you might not be interested by the method "csv" and so on. The hard work is done by the count method.

EDIT: If you just wanted to select certain values of you CSV file. I suggest taking a look at the method "values_at": http://www.ruby-doc.org/core-1.9.3/Array.html#method-i-values_at

csv.values_at(0..1).count {|x| x.last.to_i > 1000}
Sign up to request clarification or add additional context in comments.

3 Comments

How could i adress elements here? I do not want to count "all", but only for certain elements (i editted the question to be clearer? could you briefly explain me the def @ and || part? thank you a lot!
@PeriodicProgrammer Explaining how basic Ruby constructs like method definitions and instance variables work is far beyond the scope of your question, and an indicator that you should read a Ruby tutorial or book.
thank you for the help. yes you are right i should go further into the docs, but i only try to verify a small programm, and there are (which is very nice) a big variety of different ways of conducting it in ruby.. in any case thanks your fast support

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.