Method: CSV::Table#values_at
- Defined in:
- lib/csv/table.rb
#values_at(*indices_or_headers) ⇒ Object
:call-seq:
table.values_at(*indexes) -> array_of_rows
table.values_at(*headers) -> array_of_columns_data
If the access mode is :row or :col_or_row, and each argument is either an Integer or a Range, returns rows. Otherwise, returns columns data.
In either case, the returned values are in the order specified by the arguments. Arguments may be repeated.
Returns rows as an Array of CSV::Row objects.
No argument:
source = "Name,Value\nfoo,0\nbar,1\nbaz,2\n"
table = CSV.parse(source, headers: true)
table.values_at # => []
One index:
values = table.values_at(0)
values # => [#<CSV::Row "Name":"foo" "Value":"0">]
Two indexes:
values = table.values_at(2, 0)
values # => [#<CSV::Row "Name":"baz" "Value":"2">, #<CSV::Row "Name":"foo" "Value":"0">]
One Range:
values = table.values_at(1..2)
values # => [#<CSV::Row "Name":"bar" "Value":"1">, #<CSV::Row "Name":"baz" "Value":"2">]
Ranges and indexes:
values = table.values_at(0..1, 1..2, 0, 2)
pp values
Output:
[#<CSV::Row "Name":"foo" "Value":"0">,
#<CSV::Row "Name":"bar" "Value":"1">,
#<CSV::Row "Name":"bar" "Value":"1">,
#<CSV::Row "Name":"baz" "Value":"2">,
#<CSV::Row "Name":"foo" "Value":"0">,
#<CSV::Row "Name":"baz" "Value":"2">]
Returns columns data as row Arrays, each consisting of the specified columns data for that row:
values = table.values_at('Name')
values # => [["foo"], ["bar"], ["baz"]]
values = table.values_at('Value', 'Name')
values # => [["0", "foo"], ["1", "bar"], ["2", "baz"]]
734 735 736 737 738 739 740 741 742 743 744 745 746 |
# File 'lib/csv/table.rb', line 734 def values_at(*indices_or_headers) if @mode == :row or # by indices ( @mode == :col_or_row and indices_or_headers.all? do |index| index.is_a?(Integer) or ( index.is_a?(Range) and index.first.is_a?(Integer) and index.last.is_a?(Integer) ) end ) @table.values_at(*indices_or_headers) else # by headers @table.map { |row| row.values_at(*indices_or_headers) } end end |