From 93030d0e4d93683346648b25bd69a3f33a5f0486 Mon Sep 17 00:00:00 2001 From: jeg2 Date: Thu, 27 Dec 2012 16:15:53 +0000 Subject: * lib/csv.rb: Added more Hash methods to CSV::Row. git-svn-id: svn+ssh://ci.ruby-lang.org/ruby/trunk@38633 b2dd03c8-39d4-4d8f-98ff-823fe69b080e --- lib/csv.rb | 38 +++++++++++++++++++++++++++++++++++++- 1 file changed, 37 insertions(+), 1 deletion(-) (limited to 'lib') diff --git a/lib/csv.rb b/lib/csv.rb index a0209223c2..279890e7e0 100644 --- a/lib/csv.rb +++ b/lib/csv.rb @@ -274,7 +274,7 @@ class CSV # field( header, offset ) # field( index ) # - # This method will fetch the field value by +header+ or +index+. If a field + # This method will return the field value by +header+ or +index+. If a field # is not found, +nil+ is returned. # # When provided, +offset+ ensures that a header match occurrs on or later @@ -291,6 +291,42 @@ class CSV end alias_method :[], :field + # + # :call-seq: + # fetch( header ) + # fetch( header ) { |row| ... } + # fetch( header, default ) + # + # This method will fetch the field value by +header+. It has the same + # behavior as Hash#fetch: if there is a field with the given +header+, its + # value is returned. Otherwise, if a block is given, it is yielded the + # +header+ and its result is returned; if a +default+ is given as the + # second argument, it is returned; otherwise a KeyError is raised. + # + def fetch(header, *varargs) + raise ArgumentError, "Too many arguments" if varargs.length > 1 + pair = @row.assoc(header) + if pair + pair.last + else + if block_given? + yield header + elsif varargs.empty? + raise KeyError, "key not found: #{header}" + else + varargs.first + end + end + end + + # Returns +true+ if there is a field with the given +header+. + def has_key?(header) + !!@row.assoc(header) + end + alias_method :include?, :has_key? + alias_method :key?, :has_key? + alias_method :member?, :has_key? + # # :call-seq: # []=( header, value ) -- cgit v1.2.3